Fetchtype.LAZY的行为类似于Fetchtype.EAGER 与一对一映射



我有user(user_idPK(实体One-to-One它与mentor_profile实体有关联。那么mentor_profileOne-to-Manymentor_history有关联。
mentor_profile的主键是来自用户表的共享PK,即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;

但是,当触发对userselect查询时,即使我使用的是 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=?

这个模型背后的基本思想是:用户可以有类似的角色,如导师,例如培训师。如果用户是导师,则有某些导师特定的列。例如,他/她何时开始指导,他是否可以接受指导等。由于这些详细信息特定于就业(导师,培训师(,因此无法存储在用户表下。因为使用这种设计,如果用户是导师,那么与培训师相关的所有列都将是空白的,这是一个糟糕的设计。根据高性能mysql,应始终避免在数据库中使用空值,它们会消耗我们的内存和性能。因此,将user的职业与xx_profile分开可以解决这个问题。

是共享密钥导致了问题吗?

懒惰不适用于一对一映射。最好改成@ManyToOne,懒惰会努力的。

最新更新