JPA: how to persist many to many relation

asdlfkjlkj

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.

Matias Elorriaga

Replace CascadeType.ALL with CascadeType.MERGE.

Also, add setters on both entities.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

JPA persist entities with one to many relation

How to delete entity with many to many relation? JPA

How to correctly persist one-to-many to many relation

how to select child in one to many relation in jpa

detached entity passed to persist, many to many JPA

JPA many to many relation not inserting into generated table

Many to many relation not persisting in Spring JPA, Kotlin

How to Select Only Specific Children in One to Many Relation in JPA

JPA: How to have one-to-many relation of the same Entity type

How to persist many objects to database?

How to display data from multiple tables using Spring data JPA - many to many relation

How to find an entity containing a list of id (of the other entity) in a many-to-many relation on MySql/Jpa?

Persist many to many with SelectBooleanCheckbox

Spring boot: How to persist one-to-many relation separately using Repository

How to query a Many-to-Many relation with TypeORM

How to insert entity with many to many relation?

How to get unique children in a many to many relation?

How to bind a many-to-many relation in WinForms?

How to get the ids of many to many relation?

How to query many to many relation in sequelize

How to do this with a Many-to-Many relation

Jpa many to many relation, bad sql query generated

Spring Boot JPA: Many to Many relation as its own class?

Retrieveing list from a many-to-many relation with JPA/HQL

JPA/JPQL - Many-to-many relation - OrderBy doesn't work

How many Functional Dependency in this relation?

How to use one to many relation?

Eloquent many-to-many-to-many - how to load distant relation easily

Many to many relation not loading