asdlfkjlkj asdlfkjlkj - 2 months ago 11
Java Question

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.

Answer

Replace CascadeType.ALL with CascadeType.MERGE.

Also, add setters on both entities.