Hi,
I am trying to map two classes ( User and Role) using a many-to-many mapping table (TBL_USER_ROLE). The problem is when I call setRoles() in a User object and then to update(user), the new Roles are not being saved in TBL_USER_ROLE.
Please help!
DB : Sql Server 2000
Hibernate: 2.1.3
Here are User and Role classes
/**
* @hibernate.class
* table="TBL_USER"
*
*/
public class User implements Serializable
{
/** identifier field */
private Integer id;
/** persistent field */
private List roles;
/**
* @hibernate.id
* generator-class="hilo"
* type="java.lang.Integer"
* column="ID"
*
*/
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* @return
* @hibernate.bag
* table="TBL_USER_ROLE"
* cascade="all"
* inverse="true"
*
* @hibernate.collection-key
* column="USER_ID"
*
* @hibernate.collection-many-to-many
* class="com.crosslink.biz.user.Role"
* column="ROLE_ID"
*
*/
public List getRoles() {
return this.roles;
}
public void setRoles(List roles)
{
this.roles = roles;
}
/**
*
* @param role
*/
public void addRole(Role role) {
if (this.containsRole(role))
return;
else
this.getRoles().add(role);
}
}
/**
* @hibernate.class
* table="TBL_ROLE"
*
*/
public class Role implements Serializable {
/** identifier field */
private Integer id;
/**
* @hibernate.id
* generator-class="hilo"
* type="java.lang.Integer"
* column="ID"
*
*/
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.toString();
}
public boolean equals(Object o)
{
boolean retVal = false;
if(o instanceof Role)
{
Role role = (Role) o;
retVal = role.getId().intValue() == this.getId().intValue();
}
return retVal;
}
}
Here is the method that does update
/**
*/
public void update(User obj) {
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction trx = session.beginTransaction();
session.update(obj);
trx.commit();
}
catch(ObjectNotFoundException e) {
//log
}
catch(HibernateException e) {
//log
}
finally {
try { session.close() } catch (Exception e) {}
}
}
|