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