Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate OneToOne joined with unique but not primary key

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;
like image 981
Ilanh Avatar asked Jun 14 '12 08:06

Ilanh


2 Answers

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.

like image 61
tibtof Avatar answered Oct 11 '22 23:10

tibtof


Why would you want a "unique" key that's a 1-1 mapping AND a surrogate ID? It's redundant. Just make the two PKs equal as it is a 1-1 mapping.

like image 20
Jeff Watkins Avatar answered Oct 11 '22 23:10

Jeff Watkins