JPA: how to persist many to many relation
Solution 1
Replace CascadeType.ALL
with CascadeType.MERGE
.
Also, add setters on both entities.
Solution 2
I define many to many relation through @ManyToMany annotation in JPA.
I have written a code example to insert.
I think this image will help you understand
asdlfkjlkj
Updated on June 14, 2022Comments
-
asdlfkjlkj almost 2 years
I have these 2 entity with many to many relationship.
@Entity public class User { @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List<User> users = new ArrayList<User>(); } @Entity public class Language { @ManyToMany(mappedBy = "languages") private List<User> users = new ArrayList<User>(); }
I already have 20 languages saved in my language table. Now, I want to create a user and give relate that user with first language in the language table. So I did something like this
Language selectedLanguage = languageService.findById(1); stammdaten.getLanguages().add(selectedLanguage); stammdatenService.save(stammdaten);
But this gives me error
org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.outgoing.Entity.Language
. So how can I save this many to many relation. One thing to note here: I don't want to add new language. I want to add new user with already created languages. -
asdlfkjlkj over 7 yearsyour solution works but I don't understand why. I thought
CascadeType.ALL
covers all like merge, persisting etc -
TOMAS over 3 yearsWhat if you want to do that with a controller ?
-
Ali Yeganeh over 3 yearsYou need to write a service for the DAO layer and then inject the service into the controller layer.
-
TOMAS over 3 yearsOK. Thanks! But if I want to pull out the object from the view instead of hardcoding the Course(Course course = ... Course("Jee") and Student (Student student = ... Student("Ali")) from the same form. Can I do that in one Session ?
-
Ali Yeganeh over 3 yearspublic void insertStudentAndCourseManyToMany( Student[] students, Course[] courses ) { for ( Course course : courses ) { em.persist( course ); for ( Student student : students ) { student.addCourse( course ); em.persist( student ); } } }
-
TOMAS over 3 yearsThanks. But in the controller. Using model attribute. Maybe I have to make a wrapped class as I will have two objects backing a form.