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 child
  • cascade --> ALL by default
  • orphanRemoval --> true by default
  • fetch --> we use LAZY for performance reason
I use a 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:
  1. @NamedEntityGraph : this annotation tell JPA which node to load automatically. 
  2. @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

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form