Hibernate version: 3.1
Name and version of the database you are using: MySql 5
In my *:* relationship of User and Department, a join table (member_dept) is used. In java class, a HashSet is used in both side to represent this bi-directional relationship
Since the "inverse=true" can only be on one side, I set it on the Department side and hope to use User object to manage CRUD. However the requirement need Department GUI do the CRUD, too.
This cause problem: when use DepartmentDao to delete a user,
Code:
public void deleteMember(User member) {
....
department.getMembers().remove(member);
member.getDepartments().remove(this);
session.saveOrUpdate(department);
}
it has exception of violating the foreign key contraint in table member_dept;
when use DepartmentDao to add and save a user:
Code:
public void addMember(User member) {
....
department.getMembers().add(member);
member.getDepartments().add(this);
session.saveOrUpdate(department);
}
, it throws NonUniqueObjectException.
My understanding is: since only one object can manage the update of join table, and since inverse=true on Department, this object won't update that table. Therefore delete a user from Department object will of course cause fk contraint exception;
similar reason when use department object to add/save User object, "an object w/ same ID already exists in session", so that throw NonUniqueObjectException
Am I right?
My solution is (haven't tried yet): in department object
get Set of Users;
iterate through each user, call userDao.removeDepartment(dept) for delete member, or userDao.addDept(dept) for adding member;
save this user;
But I believe even if it sucess, it's a bad solution. anyone has a solution to deal with this?