Hibernate OneToOne joined with unique but not primary key

Ilanh picture Ilanh · Jun 14, 2012 · Viewed 7.3k times · Source

I have two tables:

  1. users:

    • user_id (primary)

    • etc ..

  2. users_info

    • id (primary)

    • user_id (unique)

    • etc ..

I would like to create a oneToOne relationship from user to user_info on the user_id field. Note, that it is unique but not primary. Can it be done on Hibernate? What ever I am doing, Hibernate try to use the users_info.id field instead of users_info.user_id field.

@OneToOne(mappedBy="user_id", cascade = {CascadeType.ALL}, fetch=FetchType.LAZY, optional=true)
@JoinColumn (name="user_id")    
public UserInfo getUserInfo() { return userInfo; }
public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; }
private UserInfo userInfo;

Answer

tibtof picture tibtof · Jun 14, 2012

In User you should have:

@OneToOne(mappedBy="user", cascade = CascadeType.ALL, fetch=FetchType.LAZY, optional=true)
public UserInfo getUserInfo() { return userInfo; }

And in UserInfo:

@OneToOne
@JoinColumn(name="user_id")
public User getUser() { return user; }

Have a look here. It's the second example of one-to-one mapping.