Hi -
I am using EJB3 + JPA {Hibernate 3} on Weblogic10 App server and have been facing the following problem: -
A)Table User
---------------
UserID PK
UserName
B)Table Role
---------------
RoleID PK
RoleName
C)Table UserRole {composite PK}
--------------
UserID (PK)
RoleID (PK)
UserRoleCreateDate
I have 3 Entities corresponding to these 3 tables. And their relationship is as follows: -
A) User
@OneToMany(fetch = FetchType.EAGER, mappedBy="user", cascade=CascadeType.ALL)
private Set<UserRole> userRoleCollection;
B) Role
@OneToMany(fetch = FetchType.EAGER, mappedBy="role", cascade=CascadeType.ALL)
private Set<UserRole> userRoleCollection;
C) UserRole
has a UserRolePK class with userID and roleID.
and has these relation declaration
@ManyToOne
@JoinColumn(name="ROLE_ID", insertable=false, updatable=false)
private Role role;
@ManyToOne
@JoinColumn(name="USER_ID", insertable=false, updatable=false)
private User user;
Now I have a business requirement that I should be able to add and delete user+role asscociation in UserRole table. In order to accomplish the same I have the following business methods in my EJB3 implementation class: -
Add Role to User method
public User addRole(User user, long id) {
Query q = em.createQuery("select e from Role e " +
"where e.roleId in (:roleIDs)");
q.setParameter("roleIDs", id);
List<Role> rolesTobeAdded = q.getResultList();
for(Role role : rolesTobeAdded) {
UserRolePK pk = new UserRolePK();
pk.setUserId(user.getUserId());
pk.setRoleId(role.getRoleId());
UserRole ur = new UserRole();
ur.setPk(pk);
ur.setCreatedDate(new Date());
ur.setUser(user);
ur.setRole(role);
//Add user role.
user.getTempSecUserRoleCollection().add(ur);
}
return em.merge(user);
}
This method works fine and it addes the new user role association into the UserRole table. Now come the part with the problem: -
Delete Role to User method
public User deleteRole(User user, long id) {
Set <UserRole> roleList =
user.getUserRoleCollection();
for(UserRole role: roleList) {
UserRolePK pk = new UserRolePK();
pk.setUserId(user.getUserId());
pk.setRoleId(id);
//NOTE: I have implement equals and hascode for PK class
if(role.getPk().equals(pk)) {
user.getUserRoleCollection().remove(role);
break;
}
}//end of for
return em.merge(user);
}
Now for delete from the association table, I do not want any data deleted from Role or User table. But when I inkove my delete method I do see Hibernate select queries getting executed, but it does not perform any delete on the association table. I am confused as to why insert into the association table works and not delete? I will would be grateful if someone can provide me an answer to this question.
Best Regards,
Dece
|