Hibernate 关联关系映射配置
程序员文章站
2022-04-22 18:04:13
...
Hibernate 关联关系映射配置
-
问题背景
- 一个部门下有多个员工,每个员工只属于一个部门
- 员工对部门(多对一)
- 部门对员工(一对多)
-
配置关联关系
-
实体类
Employee.java
public class Employee { private Department department; private Integer employeeID; private String employeeName; private String sex; private Date birthday; private Date joinDate; private String employeeNo; private String username; private String password; //getter setter }
Department.java
public class Department { private Set<Employee> employees=new HashSet<Employee>(); private Integer departmentID; private String departmentName; private String departmentDesc; //getter setter }
-
Employee.hbm.xml中多对一的配置
<!--关联关系映射--> <many-to-one name="department" class="domain.Department" column="depID"/>
-
Department.hbm.xml中一对多的配置
<!--关联关系映射--> <set name="employees"> <key column="depID"/> <one-to-many class="learn.ssh_employee.domain.Employee" /> </set>
-
-
附完整版配置
Employee.hbm.xml中多对一的配置
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="learn.ssh_employee.domain.Employee" table="employee"> <id name="employeeID" column="employeeID"> <generator class="native"/> </id> <property name="employeeName" column="employeeName" length="20"/> <property name="sex" column="sex" length="10" /> <property name="birthday" column="birthday"/> <property name="joinDate" column="joinDate"/> <property name="employeeNo" column="employeeNo" length="20"/> <property name="username" column="username" length="20"/> <property name="password" column="password" length="20"/> <!--关联关系映射--> <many-to-one name="department" class="learn.ssh_employee.domain.Department" column="depID"/> </class> </hibernate-mapping>
Department.hbm.xml中一对多的配置
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="learn.ssh_employee.domain.Department" table="department"> <id name="departmentID" column="departmentID"> <generator class="native"/> </id> <property name="departmentName" column="departmentName" length="20"/> <property name="departmentDesc" column="departmentDesc" /> <!--关联关系映射--> <set name="employees"> <key column="depID"/> <one-to-many class="learn.ssh_employee.domain.Employee" /> </set> </class> </hibernate-mapping>