Reputation: 14727
I am using Spring Data and Hibernate for my web app. I have the following entity class.
@Entity
public class Purchase{
@Id
@GeneratedValue
private Long id;
@OneToMany(fetch = FetchType.LAZY)
private List<Item> items;
// etc
}
I need to eagerly load a number of purchases including their associated items in each purchase. I am using the following JPQL:
@Query("select p from Purchase p join fetch p.items where r.id in (:ids)")
List<Purchase> getPurchasersByIds(@Param("ids") List<Long> ids);
However, the number of returned objects is NOT the number of purchases, but the number of items. For example, if I have only one purchase, which contains two items, then the returned list would contain two objects of the same purchase. How can I make it return only one Purchase object with two eagerly load items?
Upvotes: 0
Views: 308
Reputation: 40298
I think this is according to spec (unfortunately). See JPA 2.1, ch. 4.4.5.3 "Fetch Joins":
The following query returns a set of departments. As a side effect, the associated employees for those departments are also retrieved, even though they are not part of the explicit query result. [...]
SELECT d FROM Department d LEFT JOIN FETCH d.employees WHERE d.deptno = 1
[...] Hence, for example, if department 1 has five employees, the above query returns five references to the department 1 entity.
Upvotes: 1