asdlfkjlkj asdlfkjlkj - 1 year ago 68
Java Question

JPA: how to persist many to many relation

I have these 2 entity with many to many relationship.

public class User {

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<User> users = new ArrayList<User>();

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);

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 Source

Replace CascadeType.ALL with CascadeType.MERGE.

Also, add setters on both entities.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download