Hibernate OneToOne relationship

被刻印的时光 ゝ 提交于 2019-12-11 18:34:30

问题


I have two persistence entity: User and UserDetail. They have one-to-one relationship. I use hibernate annotations. But I am getting in my database several objects of user information for one same user. Apparently my knowledge of Hibernate annotations are not so good to solve this problem.

User class:

@Entity
@Table(name = "USER")
public class User {

   @Id
   @GeneratedValue
   @Column(name = "ID")
   private Long id; 

   @Column(name = "NAME")
   private String name; 

   @Column(name = "PASSWORD")
   private String password;

   @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
   private UserDetail userDetail;

   // setters and getters

}

UserDetail class:

@Entity
@Table(name = "USER_DETAIL")
public class UserDetail {  

   @OneToOne
   @JoinColumn(name = "USER_ID")
   private User user;

   // other fields

}

I use this in my code as follows:

UserDetail userDetail = new UserDetail();
userDetail.setInfo(info);
userDetail.setUser(seventhUser);
hibernateTemplate.saveOrUpdate(userDetail);

And everything works properly. Here's what my table USER_DETAIL:

But when I try to change user information, I get an incorrect behavior. I get following table after I again set user information:

UserDetail newUserDetail = new UserDetail();
newUserDetail.setInfo(newInfo);
newUserDetail.setUser(seventhUser);
hibernateTemplate.saveOrUpdate(newUserDetail);

Why the same two objects of information correspond to one user?? I have One-To-One relationship. How can I avoid this? What am I doing wrong?


回答1:


If you want to modify an existing UserDetail, then you must set its ID, or get it from the session and modify it. Else, Hibernate thinks it's a new one that must be saved, since it doesn't have any ID.

UserDetail existingUserDetail = session.get(UserDetail.class, theUserDetailId);
existingUserDetail.setInfo(newInfo);

To make sure you don't save two UserDetail instances for the same user, you should add a unique constraint on the USER_ID column of the UserDetail database table.



来源:https://stackoverflow.com/questions/12796459/hibernate-onetoone-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!