Hibernate One2Many ing
Multi-to-one ing and one-to-many ing:
Use the relationship between departments and employees to illustrate the problem. A Department may have multiple employees, but one employee only belongs to one department.
Development steps:
(1) Design of JavaBean, Dept (Department table) Employee table)
(2) ing
(3) test
1. Dept and Employee Javabean
Dept
package cn.itcast.one2many;import java.util.HashSet;import java.util.Set;public class Dept {private int deptId;private String deptName;private Set
emps=new HashSet
();public int getDeptId() {return deptId;}public void setDeptId(int deptId) {this.deptId = deptId;}public String getDeptName() {return deptName;}public void setDeptName(String deptName) {this.deptName = deptName;}public Set
getEmps() {return emps;}public void setEmps(Set
emps) {this.emps = emps;}}
Employee
package cn.itcast.one2many;public class Employee {private int empId;private String empName;private Dept dept;public int getEmpId() {return empId;}public void setEmpId(int empId) {this.empId = empId;}public String getEmpName() {return empName;}public void setEmpName(String empName) {this.empName = empName;}public Dept getDept() {return dept;}public void setDept(Dept dept) {this.dept = dept;}}2. ing File
Dept. hbm. xml
Employee. hbm. xml
3. Test class
Package cn. itcast. one2workflow; import org. hibernate. transaction; import org. hibernate. classic. session; import org. junit. test; import cn. itcast. utils. hibernateUtil; public class App {@ Testpublic void testOne2Many () {Session session = HibernateUtil. getSession (); Transaction transaction = session. beginTransaction (); // maintain employees by Department // 1. department Dept dept = new Dept (); dept. setDeptName (Administration Department); // 2. employee emp_lwk = new Employee (); emp_lwk.setEmpName (Li Weikang); Employee emp_hw = new Employee (); emp_hsf-setempname (Han Wei); // 3. relationship dept. getEmps (). add (emp_lwk); dept. getEmps (). add (emp_hw); // 4. save to database to save each object session. save (emp_hw); session. save (emp_lwk); session. save (dept); transaction. commit (); session. close ();}}Run the test to find the table data in the database:
We can find the foreign key constraint in the t_employee table.