Home > Enterprise >  @Onte to Many relationship without child duplication
@Onte to Many relationship without child duplication

Time:10-29

I have two classes Ingredient and Allergen, and I want to persist it.

Ingredient has a One to many relationship with Allergen

public class Ingredient() {
   @OneToMany
   List<Allergen> allergens;
}

The problem is that every time I save a new object of Ingredient, then creates one Allergen in Allergen table pera each that appears in the Ingredient allergen list. For example if an ingredient has a inside the list "gluten", and another ingredient has the same allergen then the table Allergens contains a duplication of same allergen, how can avoid this behavior ?. I have tried assigning the same Allergen id but not works.

CodePudding user response:

I think you need to search for allergens which are already in DB. Make search query which is searching by name and you search do I already have "gluten".

If yes get this object and add it to the allergens of the new Ingredient. This way the id will be set inside the Allergen and the JPA session will know that this entity was in DB hopefully it will not duplicate.

Also please check documentation of the method that you are using for saving in db as it can have impact on your code. For example: What's the difference between session.persist() and session.save() in Hibernate?

  • Related