I have a datamodel, which has:
User
entity which has a few fields specific to 2 users in the application UserDetails
, which contains details specific to one particular type of user in the application besides the fields in User
entity Both entities share the same primary key. I am new to JPA. What kind of mappings should be there between the two?
@Entity
class User{
@Id
@Column(name="USER_ID")
private int id;
}
@Entity
class UserDetails{
@Id
@OneToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "USER_ID")
private User user;
...
}
The above mapping gives issues on fetching UserDetails
for a particular User
.
It requires that both Entities share the same primary key USER_ID.
You didn't mention the issues with the above mapping. It looks OK, but I would use a separate primary key for UserDetails
table.
@Entity
class UserDetails{
@Id
private int id;
@OneToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "USER_ID")
private User user;
...
}
Also, it is a good practise to use bidirectional relationships , for eaiser navigation ie getting user details from User
, you would just use user.getUserDetails();
so in User
class:
@Entity
class User{
@Id
@Column(name="USER_ID")
private int id;
@OneToOne(mappedBy = "user")
private UserDetails userDetails;
}
In this case use OneToOne
relationship. But make sure your database table UserDetails
has foreign key relationship to User
table. Use below code to implement it using JPA
and Hibernate
.
@Entity
class User{
@Id
@Column(name="USER_ID")
private int id;
// getters and setters
}
@Entity
class UserDetails{
@Id
@Column(name="USER_DETAILS_ID")
private int userDetailsId;
@OneToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
// getters and setters
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.