File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Problem in Many to Many mapping - Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Problem in Many to Many mapping - " Watch "Problem in Many to Many mapping - " New topic

Problem in Many to Many mapping -

hildich kilal
Ranch Hand

Joined: Aug 25, 2008
Posts: 44
Hello ,
I have two entities User and Role and they have Many to many relationship.
Both are pre - populated with values in database. There is a GUI where we can assign / remove roles to a user.

When i remove roles from an User it works fine and removes the link from join table 'user_role'. But when i add a role to collection in User it also tries to insert it in 'Role' table and throws "org.hibernate.exception.ConstraintViolationException"

Looks like I haven't defined the mapping correctly. ANy pointers will be helpful

User entity mapping to Role

Role entity doesn't have any mapping defined to User entity in it.

We have 3 tables User, Role and Use_Role.

To remove add role following is code in DAO.

So remove works fine and clearly deletes entry only from User_Role table.
"Hibernate: delete from user_role where t_user_name=? and roles_name=?"
But adding a role to user throws above mentioned exception and show SQL clearly shows and attempt to add Role entity in Role table.

"Hibernate: insert into role (description, propString, name) values (?, ?, ?)"

Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

How do you get the Role in your example?

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
hildich kilal
Ranch Hand

Joined: Aug 25, 2008
Posts: 44
Wouter Oet wrote:How do you get the Role in your example?

Role is get as a (collection) of entities and populated in GUI. There it is just a POJO as it is out of PersistenceContext.
After user selects a particular role from select list it is passed as it is a Pojo in DAO. Primary key of Role is 'Name'.

My understanding is that as soon as i add this role in the the role should also get merged. But that is not happening.
I tried merging the Role explicitely. But then I get NonUniqueObject exception at time of commit.

here is the code from DAO

I agree. Here's the link:
subject: Problem in Many to Many mapping -
It's not a secret anymore!