简体   繁体   中英

How Can I avoid N+1 issue in JPA with several relationship?

I have the following entities:

@Entity
@Table(name="table1")
public class Entity1 {

    @Id
    private Integer id;

    @OneToMany(mappedBy = "entity1")
    private List<Entity2> entities2;
}

@Entity
@Table(name="table2")
public class Entity2 {

    @Id
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name="id")
    private Entity3 entity3;
}

Using Criteria API I have tried:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Entity1> query = cb.createQuery(Entity1.class);

Root<Entity1> entity1= query.from(Entity1.class);
entity1.fetch("entities2", JoinType.LEFT);
entity1.fetch("entities2", JoinType.LEFT).fetch("entity3", JoinType.LEFT);

But when the query is executed:

query.select(entity1).where(cb.and(predicates.toArray(new Predicate[predicates.size()]))));
List<Entity1> entities1 = entityManager.createQuery(query).getResultList();

Multiple queries intead one are executed (related to Entity 3). I think the problem is beacuse the relationship is inside another one. Because when you fecth the first join, there are not several queries.

I would appreciate your help. Thank so much

By default the relationships wich are like Collections the hibernate deal how lazy, if you defined relationship how Lazy and not received LazyLoadException check your config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM