例子:Dept和Emp是一对多的关系
Emp:
public class Emp implements java.io.Serializable {
private Integer id;
private Dept dept;
private String name;
private int turn;
......
}
Dept:
public class Dept implements java.io.Serializable {
private Integer id;
private String name;
private List<Emp> emps = new ArrayList();
......
}
Emp.hbm.xml:
<many-to-one name="dept" class="Dept">
<column name="dept_id" />
</many-to-one>
Dept.hbm.xml:
<list name="emps" cascade="all">
<key column="dept_id"/>
<list-index column="turn" base="0"/>
<one-to-many class="Emp" />
</list>
Session s = HbnUtil.getSession();
Transaction transaction = s.getTransaction();
transaction.begin();
Emp emp = new Emp();
emp.setName("kobe");
Dept dept = new Dept();
dept.setName("Lakers");
emp.setDept(dept);
dept.getEmps().add(emp);
s.save(emp);
s.save(dept);
transaction.commit();
如果<list>中添加属性inverse=”true”,则turn由手工维护,
只有当inverse=”false”时,才是由hibernate自动维护turn。
也就是下标必须由一的一方来维护。