07-hibernate一对多实例

重要的是看如何使用实体类的映射文件配置一对多关系。

以及如何用他们之间建立的关系由一找到多的数据。


首先一对多的配置方式:

以部门和员工的关系进行说明:从部门角度看,是一对多,所以部门类中要表示多的配置。


对应的映射文件配置主要是对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();
			}
		}
	}
	
}

代码下载地址:

hibernate一对多实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会编程的阿强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值