When you create a subquery on entity which is joined then additional inner join is created in SQM query. Entities:
@Entity
public class EntityA {
@Id
private Integer id;
@OneToMany
private List<EntityB> bCollection;
}
@Entity
public class EntityB {
@Id
private Integer id;
@ManyToOne
private EntityA a;
@ElementCollection
private final Set<EntityC> cCollection = new HashSet<>();
}
@Embeddable
public class EntityC {
private LocalDateTime date;
private Long value;
}
Query creation:
entityManager.createQuery("""
select distinct a.id, b.id, c.value
from EntityA a
left join EntityB b on b.a.id = a.id
left join b.cCollection as c
where (c.date = (select max(c2.date)
from b.cCollection as c2) or c.date is null)
""");
entityManager.createQuery("""
select distinct b.id, c.value
from EntityB b
left join b.cCollection as c
where (c.date = (select max(c2.date)
from b.cCollection as c2) or c.date is null)
""");
In the first query we receive following result:
There’s the additional inner join to c2_0, which is never used. In the second query this is the result:
There are not additional joins. First query with Hibernate 5.6.15:
It doesn’t have any additional inner join. |