I am having user
(user_id
PK) entity which has One-to-One
association with mentor_profile
entity. Then the mentor_profile
has One-to-Many
association with mentor_history
.
The primary key of mentor_profile
is the shared PK from user table i.e user_id.
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "user_id", unique = true, nullable = false)
private Integer userId;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
private MentorProfile mentorProfile;
mentor_profile
@Entity
@Table(name = "mentor_profile")
public class MentorProfile {
@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "user_id", unique = true, nullable = false)
private int userId;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private User user;
@Column(name = "is_looking_mentee")
private Boolean isLookingMentee;
But when a select
query on user
is triggered, all the associated One-to-One entities(with shared key of user) also get selected even I am using FetchType>LAZY.
Hibernate: select user0_.user_id as user_id1_43_, user0_.about as about2_43_ ............ from user user0_ where user0_.first_name=?
Hibernate: select mentorprof0_.user_id as user_id1_29_0_, ............. from mentor_profile mentorprof0_ where mentorprof0_.user_id=?
Hibernate: select trainerpro0_.user_id as user_id1_42_0_, ............. from trainer_profile trainerpro0_ where trainerpro0_.user_id=?
The basic idea behind this model is: user can have similar roles like mentor, e.g trainer. And if the user is mentor, there are certain mentor specific columns. E.g when he/she started mentoring, if he is available to mentoring etc. Since these details are employment(mentor, trainer) specific, these cannot be stored under user table. Because with that design, if a user is mentor then all the columns related to trainer will be blank, which is a bad design. According to high performance mysql, one should always avoid null values in the DB, they cost us memory and performance. So separating the user
's profession with xx_profile
solves this problem.
Is it the shared-key which is causing the issue?