Hibernate的集合一对多与多对一

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate的集合一对多与多对一相关的知识,希望对你有一定的参考价值。

需求:   部门与员工

                     一个部门有多个员工;       【一对多】

                     多个员工,属于一个部门    【多对一】

 技术分享


 

1、javaBean

  ——Dept.java

package com.gqx.onetomany;

import java.util.HashSet;
import java.util.Set;

public class Dept {
	private int deptId;
	private String deptName;
	//部门对应的多个员工 (一对多)
	private Set<Employee> emps=new HashSet<Employee>();
	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<Employee> getEmps() {
		return emps;
	}
	public void setEmps(Set<Employee> emps) {
		this.emps = emps;
	}

	
}
	

——Employee.java

package com.gqx.onetomany;

public class Employee {
	private int empId;
	private String empName;
	private double salary;
	//员工与部门	(多对一)
	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 double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public Dept getDept() {
		return dept;
	}
	public void setDept(Dept dept) {
		this.dept = dept;
	}
	
	
	
}

 2、一对多与多对一在映射文件中的表现

多个员工对应一个部门(Employee.hbm.xml)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping  package="com.gqx.onetomany">

	<class name="Employee"  table="t_Employee">
		<id name="empId" >
			<generator class="native"></generator>
		</id>
		<property name="empName" length="20"></property>
		<property name="salary" type="double"></property>
		
		<!-- 
			多对一映射配置
			Employee映射关键点
			1、映射的部门属性	dept
			2、映射的部门对象,对应的字段	dept_id	
			3、部门的类型
		 -->
		 <many-to-one name="dept" column="dept_id" class="Dept"></many-to-one>
	</class>

</hibernate-mapping>

一个部门对应多个员工(Dept.hbm.xml)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping  package="com.gqx.onetomany">
	<class name="Dept" table="t_Dept" >
		<id name="deptId">
			<generator class="native"></generator>
		</id>
		<property name="deptName" length="20"></property>
		
		<!-- 
			一对多关联映射配置(通过部门管理到员工)
			Dept 映射关键点
			1、指定映射的集合属性:		"emps"
			2、集合属性对应的集和表		"t_employee"
			3、集合表的外键字段			 "t_employee中的dept_id
			4、集合元素的类型
		 -->
		 <set name="emps" table="t_Employee">
		 	<key column="dept_id"></key>
		 	<one-to-many class="Employee"/>
		 </set>
	</class>
</hibernate-mapping>

 3、写测试类进存储

package com.gqx.onetomany;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class Demo {
	private static SessionFactory sf;
	static{
		sf=new Configuration().
				configure().
				addClass(Dept.class).addClass(Employee.class)
				.buildSessionFactory();
	}
	/**
	 * 保存:部门方【一的一方】
	 */
	@Test
	public void test() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		//部门对象
		Dept dept=new Dept();
		dept.setDeptName("前端组");
		//员工对象
		Employee emp1=new Employee();
		emp1.setEmpName("张三");
		Employee emp2=new Employee();
		emp2.setEmpName("李四");
		//关系
		dept.getEmps().add(emp1);
		dept.getEmps().add(emp2);
		//保存
		session.save(dept);
		session.save(emp1);
		session.save(emp2);
		
		
		session.getTransaction().commit();
		session.close();
		
		/* 结果
		 *Hibernate: insert into t_Employee (empName, salary, dept_id) values (?, ?, ?)
		 *Hibernate: insert into t_Employee (empName, salary, dept_id) values (?, ?, ?)
		 *Hibernate: insert into t_Dept (deptName) values (?)
		 *Hibernate: update t_Employee set deptId=? where empId=?
		 *Hibernate: update t_Employee set deptId=? where empId=?
		 *
		 *为什么会有五条sql语句?
		 *开始的时候先插入员工,并没有部门,一旦部门加入后,通过update的语句维护两者的关系
		 */
	}
	
	/**
	 * 保存:员工方【多的一方】
	 */
	@Test
	public void test2() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		//部门对象
		Dept dept=new Dept();
		dept.setDeptName("运维组");
		//员工对象
		Employee emp1=new Employee();
		emp1.setEmpName("王五");  
		Employee emp2=new Employee();
		emp2.setEmpName("老刘");
		//关系
		emp1.setDept(dept);
		emp2.setDept(dept);
		//保存
		session.save(emp1);
		session.save(emp2);
		session.save(dept);
		
		
		session.getTransaction().commit();
		session.close();
		
		/* 结果
		 *Hibernate: insert into t_Dept (deptName) values (?)
		 *Hibernate: insert into t_Employee (empName, salary, dept_id) values (?, ?, ?)
		 *Hibernate: insert into t_Employee (empName, salary, dept_id) values (?, ?, ?)
		 *
		 *如果将session.save(dept)放到两个员工的下方 结果为:
		 *	Hibernate: insert into t_Employee (empName, salary, dept_id) values (?, ?, ?)
			Hibernate: insert into t_Employee (empName, salary, dept_id) values (?, ?, ?)
			Hibernate: insert into t_Dept (deptName) values (?)
			Hibernate: update t_Employee set empName=?, salary=?, dept_id=? where empId=?
			Hibernate: update t_Employee set empName=?, salary=?, dept_id=? where empId=?
		 */
	}

}

存储之后,如果要获取数据,则、

package com.gqx.onetomany;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class DemoGet {
	private static SessionFactory sf;
	static{
		sf=new Configuration().
				configure().
				addClass(Dept.class).addClass(Employee.class)
				.buildSessionFactory();
	}
	@Test
	public void test() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		//通过部门方获取另外一方
		Dept dept=(Dept)session.get(Dept.class, 1);
		System.out.println(dept.getDeptName());
		Set<Employee> set=dept.getEmps();
		Iterator<Employee> iterators=set.iterator();
		for (Iterator iterator = set.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmpName());
		}
		
		
		session.getTransaction().commit();
		session.close();
		
	}
	@Test
	public void test2() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		//通过员工方获取另外一方
		Employee employee=(Employee)session.get(Employee.class, 1);
		System.out.println(employee.getEmpName());
		System.out.println(employee.getDept().getDeptName());
		
		
		session.getTransaction().commit();
		session.close();
		
	}
	
	
}

总结:

  在一对多与多对一的关联关系中,保存数据最好的通过多的一方来维护关系,这样可以减少update语句的生成,从而提高hibernate的执行效率!

  配置一对多与多对一,这种叫“双向关联”

  只配置一对多,           叫“单项一对多”

  只配置多对一,           叫“单项多对一”

注意:

         配置了哪一方,哪一方才有维护关联关系的权限!


js:强大的splice

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
</head>

<body>
    <input type="text">
    <br>
    <input type="checkbox" value="html">html
    <br>
    <input type="checkbox" value="js">js
    <br>
    <input type="checkbox" value="css">css
    <br>
    <input type="checkbox" value="jquery">jquery
    <br>
    <script>
    /* 	array.splice(start, deleteCount[, item1[, item2[, ...]]])
        哪一位开始修改内容 / 移除的数组元素的个数 / 要添加进数组的元素。如果不指定,则 splice() 只删除数组元素
        var arr = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘];
    	var a = arr.splice( 1 , 2 , ‘x‘ , ‘y‘ ,‘z‘ );
    	console.log(arr);
        会打印出["a", "x", "y", "z", "d", "e", "f"]
        将arr中索引为1(从0开始)的后两位删除,同时添加‘x‘,‘y‘,‘z‘
        */
    var aInput = document.getElementsByTagName(‘input‘);
    for (var i = aInput.length - 1; i >= 0; i--) {
        aInput[i].onclick = function() {
            if (this.checked) {
                if (aInput[0].value == ‘‘) {
                    aInput[0].value += this.value;
                } else {
                    aInput[0].value += ‘,‘ + this.value;
                }
            } else {
                var arr = aInput[0].value.split(‘,‘);
                for (var i = arr.length - 1; i >= 0; i--) {
                    if (arr[i] == this.value) {
                        //第二个参数表示从数组中的第i个元素开始删除一个元素
                        console.log(arr);
                        arr.splice(1, 1);
                        console.log(arr);
                    }
                }
                aInput[0].value = arr;
            }
        }
    }
    </script>
</body>

</html>

 

以上是关于Hibernate的集合一对多与多对一的主要内容,如果未能解决你的问题,请参考以下文章

hibernate关联总结

一对一与多对多与重复条目

hibernate笔记

Hibernate框架--对象的状态,缓存, 映射

服务器一对多与多对多处理

Hibernate:在 ***Error 中与多对多结果合并