Comprehensive JPA Problem

I am working on a project with some unusual entity relationships that I'm having problems with JPA. There are two relevant objects; User and let the other X. The user has a one-to-many relationship and a two-to-one relationship to X. It basically looks like this:

[Custom Object]

@OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true)  
private List<X> xList;

@OneToOne  
@JoinColumn(name = "active_x1_id")  
private X activeX1;  

@OneToOne  
@JoinColumn(name = "active_x2_id")  
private X activeX2;

[Object X]

@ManyToOne()  
@JoinColumn(name="user_id")  
private User user;

When saving a new user, I also want to save two x-entities (one for activeX1 and one for activeX2) in one transaction. Jpa handles this weird, the log looks like this:

INSERT INTO X VALUES (...) // x1  
INSERT INTO USERS VALUES (...)  
INSERT INTO X() VALUES (...) // x2  
UPDATE USERS SET ...  
UPDATE X VALUES (...) // updates x1  

NOT NULL . ? , JPA ? , JPA . .

+3
2

EntityManager.flush, JPA .

user.setProperties();
em.persist();
em.flush();

X x1 = X ();
user.setActiveX1 (x1);
X x2 = X ();
user.setActiveX2 (2);

- ActiveX- , , X.

0

@NotNull? , . . - ,

User user = ...;

if ( user.getActiveX1().getId() == null ) {
      entityManager.persist( user.getActiveX1() );
} else {
      entityManager.merge( user.getActiveX1() );
}

if ( user.getActiveX2().getId() == null ) {
      entityManager.persist( user.getActiveX2() );
} else {
      entityManager.merge( user.getActiveX2() );
}

if ( user.getId() == null ) {
      entityManager.persist( user );
} else {
      entityManager.merge( user );
}
0

Source: https://habr.com/ru/post/1780877/


All Articles