0

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.

1 Answers1

1

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?

Level_Up
  • 789
  • 5
  • 19
  • But, in theory if a I add manually the id of the allergen then has to update the entry, not create another one. I mean set id to 1, but when I execute the code assign another id like the id were null. – Javier Rius Oct 28 '22 at 19:10
  • It is not the same because behind JPA implementation (most commonly Hibernate) the entity is actually managed by Hibernate. So to be managed by Hibernate first you need to connected it with request (select). You can check article like this to understand more: https://www.baeldung.com/hibernate-entity-lifecycle – Level_Up Oct 28 '22 at 19:51
  • In your case your entities are detached before persisted in database. And according to the article you can read this: A detached entity is just an ordinary entity POJO whose identity value corresponds to a database row. The difference from a managed entity is that it's not tracked anymore by any persistence context. So Hibernate doesn't know that this entity is already in the database – Level_Up Oct 28 '22 at 19:59
  • Thanks for your answer, It's not what I want to hear, but if is the common behavior of hibernate, nothing can be done. So If I want not duplicate a existing register of Allergen, when I save Ingredient object I have to create a loop checking if id exist and in true case replace the allergen instance of the allergen list. – Javier Rius Oct 29 '22 at 09:54