简体   繁体   中英

Hibernate OneToOne relationship

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 : 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM