Hibernate Parent / Child SELECT N + 1 Issue

I create the following mapped superclass that provides a basic implementation for the parent / child relationship to create a parent / child list for unlimited nesting of elements (e.g. categories)

@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 using a fetch join for the parent and children, one choice loads all the records, and I can cross the tree with pleasure. my problem arises when I point to get a node in a tree. I want node and all its children to be in the same element. below is hql to load the whole table:

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 name node, i.e.:

where tree.name = :name

hibernate node, , SELECT N + 1. , (- tree.name =: name), HQL, node ?

, node

,

+3
1

@BatchSize?

@BatchSize(size = 20)

:

@OneToMany(mappedBy = ..., fetch = FetchType.LAZY)
@BatchSize(size = 20)
public SortedSet<Item> getItems() { ... }

, HQL, n + 1. , , HQL.

+1

Source: https://habr.com/ru/post/1757726/


All Articles