[英]Hibernate Parent/Child SELECT N+1 issue
I jave the following mapped superclass that provides a basic implementation for a parent/child self relationship to create a parent/child list for unlimited nesting of items (ie Categories) 我jave下面的映射超类,它提供父/子自我关系的基本实现,以创建一个父/子列表,用于无限制嵌套项(即类别)
@MappedSuperclass
public abstract class ParentChildPathEntity<N extends ParentChild> implements MaterializedPath<N> {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "parent_id")
private N parent;
@Column(name = "name", unique = true)
private String name;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<N> children = new HashSet<N>();
If I load the entire table with fetch join on the parent and children, a single select loads all the records and i can happily traverse the tree. 如果我在父项和子项上使用fetch join加载整个表,则单个select会加载所有记录,我可以愉快地遍历树。 my problem comes in when i specify to retrieve a node on the tree.
当我指定检索树上的节点时,我的问题就出现了。 i want the node and all its children in a single select.
我希望节点及其所有子节点在一个选择中。 below is the hql for loading the entire table:
下面是用于加载整个表的hql:
hql.append(String.format("tree from %s tree ", tableName));
hql.append("left join fetch tree.parent ");
hql.append("left join fetch tree.children ");
if i specify the node name, ie: 如果我指定节点名称,即:
where tree.name = :name
then hibernate retrieves the node, but when i access the children i get the SELECT N+1 issue. 然后hibernate检索节点,但当我访问孩子时,我得到SELECT N + 1问题。 I realize why this is happening, (because of the tree.name = :name) but is there a way to write the HQL so it loads the specified node and all its children?
我知道为什么会这样,(因为tree.name =:name)但有没有办法编写HQL,所以它加载指定的节点及其所有子节点?
I'm just trying to figure out a way to support a simple nested item's list where i can retrieve any parent node and its children with a single select 我只想找到一种方法来支持一个简单的嵌套项目列表,我可以通过一个选择检索任何父节点及其子节点
thanks in advance, 提前致谢,
Have you tried using the @BatchSize annotation? 您是否尝试过使用@BatchSize注释?
@BatchSize(size = 20)
Ex: 例如:
@OneToMany(mappedBy = ..., fetch = FetchType.LAZY)
@BatchSize(size = 20)
public SortedSet<Item> getItems() { ... }
Then, if you specify the join to children in your HQL, you should be able to avoid n+1 select. 然后,如果在HQL中指定对子项的连接,则应该能够避免n + 1选择。 I am not sure, offhand, if there is a way to specify the batch size in the HQL statement.
我不确定,如果有办法在HQL语句中指定批量大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.