Shafqat Shafi
Shafqat Shafi

Reputation: 1238

Hibernate : Mapping two entities

I have a question regarding mapping entities based on mapping in their tables. So, we are a team of five working on a project, one of our team mate seem to add mapping between tables in opposite direction, I'll give examples of both to let you understand what I mean.

We have two tables User and UserInfo. UserInfo has a user_id as foreign key.

1) Common Mapping I have learnt about in hibernate.

In User and UserInfo entities I usually have mappings like this:

class User{
   private int userId;
   private String userName;

   // getter and setters

}

class UserInfo{

   private int userInfoId;
   private String firstName;
   private String lastName;

   @OneToOne()
   @JoinColumn(name="user_id")
   private User user;

}

2) This is how my colleague does mapping:

class User{
   private int userId;
   private String userName;

   @OneToOne(mappedBy="user")
   @JoinColumn(name="user_id")
   private UserInfo userInfo;

   // getter and setters

}

class UserInfo{

   private int userInfoId;
   private String firstName;
   private String lastName;

   @OneToOne()
   private User user;

}

He does just opposite of what I learnt from tutorials. It is working fine somehow but I am not sure if this is the right way to map two entities. Please help.

Thanks.

Upvotes: 1

Views: 175

Answers (3)

anandchaugule
anandchaugule

Reputation: 1127

The 2nd code snippet will absolutely work fine because you are not using a bi-directional relationship.

In case if you get JsonMappingException then simply you can handle by using below annotation

You may use @JsonIgnore

Upvotes: 2

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

The difference is that the one your colleague used is bidirectional and yours is unidirectional. Bidirectional association provides navigation in both the directions. If you need userInfo object when you query user then bidirectional is what you need. If that's not the case, the one you have is more efficient than your colleague's.

I would recommend you to read this useful link on how to do one-to-one mapping efficiently: https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

Upvotes: 1

dozken
dozken

Reputation: 76

both of them should create exact same tables in DB, but second solution is better when u need call user from userInfo or userInfo from user.

ex:

User user = ...
user.getUserInfo().getFirstName();

UserInfo info = ...
info.getUser().getUserName();

PS: In this article says that most efficient to use @OneToOne with @MapsId https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

Upvotes: 2

Related Questions