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: @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 ...