Reputation: 122172
I have a class Batch
which among other properties has a list samples (of type List<Sample>
). This list is mapped via a many-to-one relation (Sample 1->n Batch). I need to be able to fetch all batches along with the amount of samples in each one. How would I do this without having to do n+1 queries?
Also, how do I map it to objects?
TypedQuery<Batch> query = entityManager.createQuery("select b from Batch b"Batch.class);
List<Batch> batches = query.getResultList()
Upvotes: 1
Views: 167
Reputation: 90497
As Batch has a property which type is List<Sample>
, the relationship of Batch to Sample is one-to-many . You should annotate @OneToMany
on the List<Sample>
inside the Batch
and annotate @ManyToOne
on Batch property inside the Sample.
To avoid n+1 problem , you can use fetch join to fetch the Batch along with its list of sample .It will cause hibernate to generate a left join of Batch and Sample such that the returned Batch instance have their sample list fully initialized.
SELECT batch FROM Batch batch join fetch batch.sampleList;
Upvotes: 2