Hibernate双向1-N关联的简单示例

1. 双向1-N关系,比如一个部门对应多个职员,可以从部门关联到全部职员,也可以从职员实体可以找到对应的部门实体


2. 部门实体Department和职员实体Employee:

package com.huey.entity;

import java.util.Set;

/**
 * 部门实体
 * @author Huey2672
 *
 */
public class Department {

	private Integer deptId;
	private String deptName;
	private Set<Employee> employees;

	public Integer getDeptId() {
		return deptId;
	}
	
	public void setDeptId(Integer deptId) {
		this.deptId = deptId;
	}
	
	public String getDeptName() {
		return deptName;
	}
	
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	
	public Set<Employee> getEmployees() {
		return employees;
	}
	
	public void setEmployees(Set<Employee> employees) {
		this.employees = employees;
	}
	
	public Department() {
	}
}
package com.huey.entity;

/**
 * 职员实体
 * @author Huey2672
 *
 */
public class Employee {

	private Integer empId;
	private String empName;
	private Department department;
	
	public Integer getEmpId() {
		return empId;
	}
	
	public void setEmpId(Integer empId) {
		this.empId = empId;
	}
	
	public String getEmpName() {
		return empName;
	}
	
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	
	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}
	
	public Employee() {
	}

}

3. 在数据库中创建表和序列(Oracle):

create table tab_dept(
	dept_id number(8) primary key,
	dept_name varchar2(20) not null
);

create table tab_emp(
	emp_id number(8) primary key,
	emp_name varchar2(20) not null,
	dept_id number(8),
	foreign key(dept_id) references tab_dept(dept_id)
);

create sequence dept_id_sequence
start with 1001
increment by 1;

create sequence emp_id_sequence
start with 1001
increment by 1;

4. 配置映射文件Department.hbm.xml和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.huey.entity">
	<class name="Department" table="tab_dept">
		<id name="deptId" column="dept_id">
			<generator class="sequence">
				<param name="sequence">DEPT_ID_SEQUENCE</param>
			</generator>
		</id>
		<property name="deptName" column="dept_name" />
		<!-- 映射集合属性 -->
		<set name="employees" table="tab_dept_emp" cascade="all" inverse="true">
			<!-- 指定关联的外键列 -->
			<key column="dept_id"/>
			<!-- 映射1-N关联实体,并指定关联实体的类型  -->
			<one-to-many class="Employee" />
		</set>
	</class>
</hibernate-mapping>
<?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.huey.entity">
	<class name="Employee" table="tab_emp">
		<id name="empId" column="emp_id">
			<generator class="sequence">
				<param name="sequence">EMP_ID_SEQUENCE</param>
			</generator>
		</id>
		<property name="empName" column="emp_name" />
		<many-to-one name="department" class="Department" column="dept_id"/>
	</class>
</hibernate-mapping>

5. 配置配置文件hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>
		<!-- Database connection settings -->
		<property name="connection.driver_class">
			oracle.jdbc.driver.OracleDriver
		</property>
		<property name="connection.url">
			jdbc:oracle:thin:@localhost:1521:orcl
		</property>
		<property name="connection.username">oa</property>
		<property name="connection.password">oa</property>
		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">1</property>
		<!-- SQL dialect -->
		<property name="dialect">
			org.hibernate.dialect.Oracle10gDialect
		</property>
		<property name="show_sql">true</property>
		<!-- Drop and re-create the database schema on startup -->
		<property name="hbm2ddl.auto">update</property>
		<mapping resource="com/huey/entity/mapping/Department.hbm.xml" />
		<mapping resource="com/huey/entity/mapping/Employee.hbm.xml" />
	</session-factory>

</hibernate-configuration>

6. 测试用例:

package com.huey.test;

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

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

import com.huey.entity.Department;
import com.huey.entity.Employee;

/**
 * 
 * @author Huey2672
 *
 */
public class EmployeeTest {
	
	private static SessionFactory sf;
	
	static {
		Configuration configuration = new Configuration()
				.configure("hibernate.cfg.xml");
		ServiceRegistryBuilder srb = new ServiceRegistryBuilder()
				.applySettings(configuration.getProperties());
		sf = configuration.buildSessionFactory(srb.buildServiceRegistry());
	}

	@Test
	public void test() throws Exception {
		Session session = sf.openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			
			Department department = new Department();
			department.setDeptName("国防部");
					
			Employee huey = new Employee();
			huey.setEmpName("huey");
			huey.setDepartment(department);
			
			Employee sugar = new Employee();
			sugar.setEmpName("sugar");
			sugar.setDepartment(department);
			
			Set<Employee> employees = new HashSet<Employee>();
			employees.add(huey);
			employees.add(sugar);		
			
			department.setEmployees(employees);		
			session.save(department);		
			
			transaction.commit();
		} catch (HibernateException e) {
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值