I have two tables:
users:
user_id (primary)
etc ..
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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With