asdlfkjlkj
asdlfkjlkj

Reputation: 2358

JPA: how to persist many to many relation

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.

Upvotes: 3

Views: 22920

Answers (2)

Ali Yeganeh
Ali Yeganeh

Reputation: 1065

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

Upvotes: 4

Matias Elorriaga
Matias Elorriaga

Reputation: 9150

Replace CascadeType.ALL with CascadeType.MERGE.

Also, add setters on both entities.

Upvotes: 6

Related Questions