重要的是看如何使用实体类的映射文件配置一对多关系。
以及如何用他们之间建立的关系由一找到多的数据。
首先一对多的配置方式:
以部门和员工的关系进行说明:从部门角度看,是一对多,所以部门类中要表示多的配置。
对应的映射文件配置主要是对set集合的配置:
员工实体类:
员工配置映射文件配置:
测试类:
package cn.itcat.hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.itcat.hibernate.domain.Department;
import cn.itcat.hibernate.domain.Employee;
public class One2Many {
public static void main(String[] args) {
Department department=add();
queryDepart(department.getId());
}
static Department add() {
Session session = null;
Transaction transaction = null;
try {
Department depart= new Department();
depart.setName("depart name");
/**保存两个员工,都属于depart Name部门*/
Employee emp1 = new Employee();
emp1.setDepartment(depart);
emp1.setName("emp name1");
Employee emp2 = new Employee();
emp2.setDepartment(depart);
emp2.setName("emp name2");
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
session.save(depart);
session.save(emp1);
session.save(emp2);
transaction.commit();
return depart;
} finally {
if (session != null) {
session.close();
}
}
}
/**
*@MethodName:queryDepart
*@Description:通过部门编号找到部门
*@param departId
*@author:徐凯强
*@return Department
*@date:2014-7-13下午11:21:05
*/
static Department queryDepart(int departId){
Session session=null;
Transaction tx=null;
try {
session = HibernateUtil.getSession();
tx=session.beginTransaction();
Department department=(Department) session.get(Department.class, departId);
/**输出部门下有多少员工*/
System.out.println("emp size:"+department.getEmps().size());
/**代理对象的初始化,懒加载有关*/
//Hibernate.initialize(department.getEmps());
tx.commit();
return department;
} finally {
if (session != null) {
session.close();
}
}
}
}
代码下载地址: