Hibernate 關聯關係對映配置
阿新 • • 發佈:2018-12-09
Hibernate 關聯關係對映配置
-
問題背景
- 一個部門下有多個員工,每個員工只屬於一個部門
- 員工對部門(多對一)
- 部門對員工(一對多)
-
配置關聯關係
-
實體類
Employee.java
public class Employee { private Department department; private Integer employeeID; private String employeeName; private String sex; private
Department.java
public class Department { private Set<Employee> employees=new HashSet<Employee>(); private Integer departmentID;
-
Employee.hbm.xml中多對一的配置
<!--關聯關係對映--> <many-to-one name="department" class="domain.Department" column="depID"/>
-
Department.hbm.xml中一對多的配置
<!--關聯關係對映--> <set name="employees"
-
-
附完整版配置
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>