Search code examples
javadatabasehibernatemany-to-many

Update record in many to many relation by Hibernate


I have two classes, Document class and Role class and a @ManyToMany relationship between them.

I tried to get a document then i get all that roles and fill the set of the document with them.

Now when i update the set of the document (insert new roles or remove existing roles) and then update the document object by session.update(doc), the Hibernate does not do any insert or delete statement into the @ManyToMany table, it only updates the document and the roles records.

Note: the lazy attribute is "lazy = true" in both tables.


Solution

  • The problem was i am using the bidirectional @ManyToMany relation (that mean the document have set of role and the role have set of document) and in this way when i create a document and adding some roles to it, even that i have to add this document to each role in the set. when i use the unidirectional @ManyToMany relation(that mean just one side have a set of the other class) i just fill the document set with some roles.

    this article is so helpful

    https://howtoprogramwithjava.com/hibernate-manytomany-unidirectional-bidirectional/