LaputaSpring 2014-06-16
Department部门和Employee员工是一对多的关系,再多的一端会有一个外键来维护关系,即多的一端是关系的维护端,少的一端为关系的被维护端。
部门实体Department.java:
/**
* 部门和员工的关系为一对多,多的一端为关系的维护端,
* 关系的维护端来负责外键的更新,少的一端无权更新外键字段。
* @author Liao
*/
public class Department {
/* 部门Id */
private Integer id;
/* 部门名称 */
private String name;
/* 部门和员工的关系(一对多) */
private Set<Employee> employees;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
员工实体Employee.java:
public class Employee {
/* 员工ID */
private Integer id;
/* 员工名称 */
private String name;
/* 员工和部门的关系(多对一) */
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
Department.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- package表示实体类的包名 -->
<hibernate-mapping package="com.lixue.bean">
<!-- class结点的name表示实体的类名,table表示实体映射到数据库中table的名称 -->
<class name="Department" table="t_department">
<id name="id" column="did">
<!-- 自增长 -->
<generator class="native"/>
</id>
<property name="name" column="dname"/>
<!-- 部门和员工的关系(一对多) -->
<set name="employees" cascade="save-update">
<key column="dept_id"/><!-- 表示在多的一端加一个字段 -->
<one-to-many class="Employee"/>
</set>
</class>
</hibernate-mapping>
Employee.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- package表示实体类的包名 -->
<hibernate-mapping package="com.lixue.bean">
<!-- class结点的name表示实体的类名,table表示实体映射到数据库中table的名称 -->
<class name="Employee" table="t_employee">
<id name="id" column="eid">
<!-- 自增长 -->
<generator class="native"/>
</id>
<property name="name" column="ename"/>
<!-- 设置Employee和Department的关系column表示和Department.hbm.xml文件的外键映射要一致 -->
<many-to-one name="department" column="dept_id"/>
</class>
</hibernate-mapping>
注:Employee为多的一端,作为关系的维护端,通过一个外键即dept_id来维护。
测试类:
public class One2ManyTest {
public static void main(String[] args) {
Session session = HibernateUtils.getSession();
Transaction transaction = session.beginTransaction();
/*创建部门并设置属性*/
Department department = new Department();
department.setName("开发部");
session.save(department);
/*创建员工并设置属性*/
Employee employee = new Employee();
employee.setName("习近平");
employee.setDepartment(department);
session.save(employee);
transaction.commit();
}
}
注:我这里只是随便测试了一下,并未关闭Session和Transaction。
Hibernate 的详细介绍:请点这里
Hibernate 的下载地址:请点这里