JPA: how to persist many to many relation

15,443

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

enter image description here

Share:
15,443
asdlfkjlkj
Author by

asdlfkjlkj

Updated on June 14, 2022

Comments

  • asdlfkjlkj
    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
    asdlfkjlkj over 7 years
    your solution works but I don't understand why. I thought CascadeType.ALL covers all like merge, persisting etc
  • TOMAS
    TOMAS over 3 years
    What if you want to do that with a controller ?
  • Ali Yeganeh
    Ali Yeganeh over 3 years
    You need to write a service for the DAO layer and then inject the service into the controller layer.
  • TOMAS
    TOMAS over 3 years
    OK. 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
    Ali Yeganeh over 3 years
    public void insertStudentAndCourseManyToMany( Student[] students, Course[] courses ) { for ( Course course : courses ) { em.persist( course ); for ( Student student : students ) { student.addCourse( course ); em.persist( student ); } } }
  • TOMAS
    TOMAS over 3 years
    Thanks. But in the controller. Using model attribute. Maybe I have to make a wrapped class as I will have two objects backing a form.