Hibernate OneToOne Joins Unique But Not Primary Key

I have two tables:

  • users:

    • user_id (primary)

    • etc.

  • users_info

    • id (primary)

    • user_id (unique)

    • etc.

I would like to create a oneToOne relation from user to user_info in the user_id field. Please note that it is unique, but not primary. Can this be done on a sleeping one? Whatever I do, Hibernate will try to use the users_info.id field instead of the u sers_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; 
+6
source share
4 answers

Why do you need a “unique” key that displays 1-1 and a surrogate identifier? This is redundant. Just make two PKs equal, since this mapping is 1-1.

+2
source

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; } 

Take a look here . This is a second one-to-one mapping example.

+2
source

Yes, that should work. In one-to-one or many-to-one, you have a primary key in the first table and a foreign key in the second table.

0
source

The mapping should work the way you defined the table column for the join. But just one thing, I'm not sure, since you defined all annotations using the getter method, this will work the same way.

0
source

Source: https://habr.com/ru/post/918069/


All Articles