Hello, when saving the entity User ( login != null ) I get an error, tell me what's wrong?

There is a users table and login , in the users table there is a login_id column (many users may have one login_id value)

Entity and communication

 @Entity(name = "users") public class User { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) private long id; @MapsId("uuid") @JoinColumn(name = "login") @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) private Login login; } @Entity(name = "login") public class Login { @Id @Column(name = "uuid") @GeneratedValue(strategy = GenerationType.AUTO) private long id; } 

I CrudRepository through CrudRepository , an error:

org.hibernate.PersistentObjectException: detached entity passed to persist: com.entity.Login

  • What is CrudRepository ? Something I do not remember in JPA such a thing. How your user and login are created, how they are saved by JPA. Can you bring a piece of CrudRepository that saves? In general, your login = new Login ()? Then probably you need to make Cascade = {CascadeType.MERGE, CascadeType.PERSIST} And even better, do everything manually, without relying on JPA magic, as it is accepted in RDBMS. Magic does not always work as it should, for the most part it is quackery. Created, saved login, Created user, assigned to him already saved login, saved. - Sergey
  • @Sergey CrudRepository - Bohdan Korinnyi 5:59 pm
  • @Sergey now the problem is if CascadeType.MERGE then a new User can be saved if Login with the specified id is in the database, but if not - an error, the same behavior for CascadeType.DETACH & CascadeType.REFRESH If you save the new User and the new Login (do not specify id ) everything will be saved to the database (only with CascadeType.ALL or CascadeType.PERSIST ), but will not work if you specify id for Login - Bohdan Korinnyi
  • CrudRepository is the same interface! By itself, he can not do anything! You must have a class with the save method containing a specific code to save the entity. - Sergey
  • Everything works noticeably as it should work. You can take and read the JPA specification. You can argue with the developers of hibernate, if there are discrepancies. Even among developers of JPA implementations, there is no agreement on some points. For example, the behavior of eclipselink in your question may be very different from hibernate. Therefore, do not trust anyone very much. Why your login with id does not work depends on the context in which this login is assigned to the user. But since the source code for creating objects and saving them is a mystery, then sort it out yourself. - Sergey

1 answer 1

In Login you must add a link to User

 @OneToMany(fetch = FetchType.EAGER, mappedBy = "loginType") private Set<User> user; 
  • Don't need 1234567 - Sergey
  • @Sergey are you talking about? - Bohdan Korinnyi