I have the following entity relationship in my data model.
Entity A: one-to-many :Entity B
Entity B: one-to-many :Entity C
Entity B: one-to-many :Entity D
Hibernate Entities:
public class EntityA {
private Integer id;
@OneToMany
private List<EntityB> entityBList;
}
public class EntityB {
private Integer id;
@ManyToOne
private EntityA entityA;
@OneToMany(fetch=FetchType.LAZY)
private List<EntityC> entityCList;
@OneToMany(fetch=FetchType.LAZY)
private List<EntityD> entityDList;
}
public class EntityC {
private Integer id;
@ManyToOne
private EntityB entityB;
}
public class EntityD {
private Integer id;
@ManyToOne
private EntityB entityB;
}
Requirement: I want to query on Entity C with join fetch of Entity B and also eagerly fetch Entity D at the same time. After the query is completed I expect that if I do entityC.getEntityB().getEntityDList()
, it should not lead to N+1 query problem in hibernate.
I was trying the following JPQL query:
select ec from EntityC ec
join fetch ec.entityB eb
join fetch eb.entityD ed
where ec.id = :id
This leads to duplicates in the result because of cross join with Entity D. Instead of one result, I get n results where n is the size of list of Entity D.
How can I avoid this? Is there any way to fetch the Entity D without cross join in JPQL?