在Hibernate中,当使用双向的一对多映射时,使用@OneToMany注释的属性会在默认情况下采用lazy fetch方式,需要使用@Fetch(FetchMode.JOIN)注释将其变为eager fetch方式。 示例代码如下:
// 父类实体 @Entity public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List children;
// getters and setters
}
// 子类实体 @Entity public class Child { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Parent parent;
// getters and setters
}
// 修改为eager fetch @Entity public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
private List children;
// getters and setters
}