I'm a beginner in Hibernate and I have the following problem.
I have one entity class called User. Each user can have a supervisor which is also an instance of User, and a set of subordinates which are User instances as well.
I use a helper table called "supervisors_subordinates" to persist supervisor-subordinate pairs.
Here is the XML mapping of the entity class User.
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="users">
<id name="id" type="long" column="id">
<generator class="increment"/>
</id>
<property name="username" not-null="true">
<column name="username" />
</property>
<set name="subordinates" table="supervisors_subordinates">
<key column="supervisor_id"/>
<many-to-many class="User" unique="true" column="subordinate_id" order-by="username"/>
</set>
<join table="supervisors_subordinates" optional="true">
<key column="subordinate_id"/>
<many-to-one name="supervisor" column="supervisor_id" not-null="true"/>
</join>
</class>
</hibernate-mapping>
And here is the code of the User class.
Code:
public class User {
private Long id;
private String username;
private User supervisor;
private Set<User> subordinates = new TreeSet<User>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User getSupervisor() {
return supervisor;
}
public void setSupervisor(User supervisor) {
this.supervisor = supervisor;
}
public Set<User> getSubordinates() {
return subordinates;
}
public void setSubordinates(Set<User> subordinates) {
this.subordinates = subordinates;
}
}
I can add supervisor for a user .
Code:
User subordinate = findUserByName("user1");
User supervisor = findUserByName("user2");
subordinate.setSupervisor(supervisor);
A new row is added to supervisors_subordinates table.
But when I delete a user the rows with references to the deleted user are not deleted from supervisors_subordinates table. I delete the user like this.
Code:
User user = findUserByName("user1");
session.delete(user);
Can anyone find the reason why the orphan rows in supervisors_subordinates table are not deleted? Thanks.