curious1
curious1

Reputation: 14727

Eagerly load lazy items from Hibernate/JPA and correct object counts

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

Answers (2)

fg78nc
fg78nc

Reputation: 5232

if you need to return number of p's, try to do select count(p)

Upvotes: 0

Nikos Paraskevopoulos
Nikos Paraskevopoulos

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

Related Questions