1

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

mgp1994
  • 59
  • 1
  • 7
  • fetch("entity3", JoinType.LEFT) should be giving you a validation exception or warning as the "entity3" doesn't exist on the entity1, so there is nothing to left join. JPA doesn't have nested fetch joins, but entity1.fetch("entities2", JoinType.LEFT).fetch("entity3", JoinType.LEFT); might work. see https://stackoverflow.com/a/55905918/496099 – Chris Nov 12 '19 at 16:57
  • Sorry, I tried that but I wrote wrong the post. It seems this doen`t work. – mgp1994 Nov 13 '19 at 07:05
  • Could be due to your 1:M as it would result in a number of rows being returned for this one object. There are many articles on the issue, but I use batch fetching (with EclipseLink), making the issue easier to deal with and don't know how to do the same in Hibernate. – Chris Nov 13 '19 at 17:34

1 Answers1

0

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.