java – 懒惰加载子项,里面有热切的集合
发布时间:2020-12-15 00:34:46 所属栏目:Java 来源:网络整理
导读:我有以下实体的问题:森林,树,叶.你可以想象森林可以有很多树木,树上有很多树叶. 我想懒得加载森林的所有树木,并渴望加载一棵树的所有树叶.我的hibernate注释代码如下所示: Forest.java @Entity@Table(name = "Forests")public class Forest implements Com
我有以下实体的问题:森林,树,叶.你可以想象森林可以有很多树木,树上有很多树叶.
我想懒得加载森林的所有树木,并渴望加载一棵树的所有树叶.我的hibernate注释代码如下所示: Forest.java @Entity @Table(name = "Forests") public class Forest implements Comparable<Forest> { @Id @Column(name = "forestnumber",length=10,nullable=false) private String number; @OneToMany(fetch=FetchType.LAZY,mappedBy="forest") private Set<Tree> trees = null; // some other attributes and methods Tree.java @Entity @Table(name = "Trees") public class Tree implements Comparable<Tree> { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="tree_id",nullable=false) private int id; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "forestnumber",nullable = false) @Fetch(FetchMode.JOIN) private Forest forest; @OneToMany(fetch=FetchType.EAGER,mappedBy="tree") @Fetch(FetchMode.JOIN) private Set<Leaf> leafs = null; // some other attributes and methods Leaf.java @Entity @Table(name = "Leafs") public class Leaf implements Comparable<Leaf> { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="leaf_id",nullable=false) private int id; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "tree_id",nullable = false) @Fetch(FetchMode.JOIN) private Tree tree; // some other attributes and methods 我的问题:加载一个林并调用getTrees()方法会产生一组选择语句. Hibernate执行一个语句来获取所有树,并为每个树执行第二个语句以收集所有叶子. 有人可以告诉我,我的问题的原因以及我如何解决它? 再见:如果我将森林树的提取策略更改为EAGER,一切正常,只有一个语句. 解决方法
您可以尝试初始化
Hibernate.initialize(forestInstance); 或者使用join提供一个查询,提供fetch以急切地检索所有孩子. 也可以看看 Is there a way to change the JPA fetch type on a method? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |