JPA : How to deal with one to many association
After reading and experiencing lot of solutions for modeling a one to many association, I'll show you the ways you can REALLY do it:
1. Using bidirectional association
the parent entity :
As you can see, I use the
@oneToMany
annotation with the following properties :mappedBy
--> parent property of the childcascade
-->ALL
by defaultorphanRemoval
-->true
by defaultfetch
--> we useLAZY
for performance reason
I use a
The child entity below implements also the
In order to retrieve the parent and the children with ONE query, we have 2 solutions:
This solution is far better for me because I can also paginate, filter and sort the results.
Set
for the collection. I provide also a helper method for adding a child to the parent (You can do the same for removing a child).The child entity below implements also the
equals
and hashCode
methods:In order to retrieve the parent and the children with ONE query, we have 2 solutions:
- @NamedEntityGraph : this annotation tell JPA which node to load automatically.
- @NamedQuery using
LEFT JOIN FETCH
These methods are both used in the below repository:
2. @ManyToOne ONLY in the child entity
The only think you need to do is to create a JPQL query for retrieving the child entities associated with the parent.
SELECT m FROM MeasuringUncertainty m WHERE m.device.identification = :identification
This solution is far better for me because I can also paginate, filter and sort the results.
Happy learning!!
Comments
Post a Comment