多对一:Employees--Department ; 多个员工对应一个部门.
<many-to-one name="depart" column="depart_id" />
public class Department {
private int id;
private String name;
public int getId() { 织梦内容管理系统
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Employee {
private int id;
private String name;
private Department depart;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepart() {
return depart;
}
public void setDepart(Department depart) {
this.depart = depart;
}
}
使用hibernate映射员工与部门的外键关系:
<hibernate-mapping package="sa.fs121.domain"> 织梦内容管理系统 copyright dedecms
<class name="Employee">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<!--
表示员工的depart属性,对应depart表中的id值,参考depart中id值表示的整个对象;
通过反射,hibernate可以找到depart对应的department类,
然后通过depart这个对象的id值,找到department表中的参考外键,
缺省情况下,hibernate外键参考的对象,就是department表中的主键id.
即:depart参考的,就是department这个表中的主键,也可以手工指定参考对象:
使用:property-ref="xxxx",进行声明
-->
<many-to-one name="depart" column="depart_id" />
</class>
</hibernate-mapping> 织梦内容管理系统
内容来自dedecms
<hibernate-mapping package="sa.fs121.domain">
<class name="Department">
<id name="id">
<generator class="native" />
</id>
<property name="name" unique="true" />
</class>
</hibernate-mapping> 本文来自织梦
本文来自织梦
static Department add() {
Session s = null;
Transaction tx = null;
try {
Department depart = new Department();
depart.setName("department1");
Employee employee = new Employee();
employee.setName("user1");
copyright dedecms
employee.setDepart(depart);
s = HibernateUtils.getSession();
tx = s.beginTransaction();
s.save(depart);
s.save(employee);
tx.commit();
return depart;
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (s != null) {
s.close();
}
} copyright dedecms
return null;
}








