Hibernate的一对多XML映射教程

来源:互联网 发布:浏览器代理软件 编辑:程序博客网 时间:2024/05/16 10:09

1。创建数据库

在这个例子中,我们将MySQL数据库。创建下面两个表在MySQL。需要注意的是Employee和Department表显示出一个一对多的关系。每个部门可以assosiated多个员工,每个员工只能有一个部门。
一个关系图

CREATE TABLE `department` (`department_id` BIGINT(20) NOT NULL AUTO_INCREMENT,`dept_name` VARCHAR(50) NOT NULL DEFAULT '0',PRIMARY KEY (`department_id`))COLLATE='latin1_swedish_ci'ENGINE=InnoDBROW_FORMAT=DEFAULTAUTO_INCREMENT=115CREATE TABLE `employee` (`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,`firstname` VARCHAR(50) NULL DEFAULT NULL,`lastname` VARCHAR(50) NULL DEFAULT NULL,`birth_date` DATE NULL DEFAULT NULL,`cell_phone` VARCHAR(15) NULL DEFAULT NULL,`department_id` BIGINT(20) NULL DEFAULT NULL,PRIMARY KEY (`employee_id`),INDEX `FK_DEPT` (`department_id`),CONSTRAINT `FK_DEPT` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`))COLLATE='latin1_swedish_ci'ENGINE=InnoDBROW_FORMAT=DEFAULT

2。Hibernate的Maven的依赖关系

我们正在使用Maven的依赖管理。复制后,在pom.xml。

文件:pom.xml的

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>net.viralpatel.hibernate</groupId><artifactId>HibernateHelloWorldXML</artifactId><packaging>jar</packaging><version>1.0-SNAPSHOT</version><name>HibernateHelloWorldXML</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.10</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate</artifactId><version>3.2.6.ga</version></dependency></dependencies></project>

3。Hibernate的模型类

员工和部门创建模型类映射到相应的数据库表。

文件“:Department.java”

package net.viralpatel.hibernate;import java.util.Set;public class Department {private Long departmentId;private String departmentName;private Set<Employee> employees;// Getter and Setter methods}

文件“:Employee.java”

package net.viralpatel.hibernate;import java.sql.Date;public class Employee {private Long employeeId;private String firstname;private String lastname;private Date birthDate;private String cellphone;private Department department;public Employee() {}public Employee(String firstname, String lastname, Date birthdate,String phone) {this.firstname = firstname;this.lastname = lastname;this.birthDate = birthdate;this.cellphone = phone;}// Getter and Setter methods}

4。Hibernate工具类

要访问Hibernate的API,我们将创建一个包装器实用工具类,它为我们提供了SessionFactory的。

文件“:HibernateUtil.java”

package net.viralpatel.hibernate;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static final SessionFactory sessionFactory = buildSessionFactory();private static SessionFactory buildSessionFactory() {try {// Create the SessionFactory from hibernate.cfg.xmlreturn new Configuration().configure().buildSessionFactory();} catch (Throwable ex) {System.err.println("Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);}}public static SessionFactory getSessionFactory() {return sessionFactory;}}

5。Hibernate映射XML(HBM)

以下是为每个enitity员工和部门的Hibernate映射文件。

文件“:Employee.hbm.xml”

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="net.viralpatel.hibernate"><class name="Employee" table="EMPLOYEE"><id name="employeeId" column="EMPLOYEE_ID"><generator class="native" /></id><property name="firstname" /><property name="lastname" column="lastname" /><property name="birthDate" type="date" column="birth_date" /><property name="cellphone" column="cell_phone" />  <many-to-one name="department" class="net.viralpatel.hibernate.Department" fetch="select">            <column name="department_id" not-null="true" />        </many-to-one></class></hibernate-mapping>

文件“:Department.hbm.xml”

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="net.viralpatel.hibernate">    <class name="Department" table="DEPARTMENT"> <id name="departmentId" type="java.lang.Long" column="DEPARTMENT_ID" ><generator class="native" /></id>        <property name="departmentName" column="DEPT_NAME"/><set name="employees" table="employee" inverse="true" lazy="true" fetch="select">            <key>                <column name="department_id" not-null="true" />            </key>            <one-to-many class="net.viralpatel.hibernate.Employee" />        </set>                </class></hibernate-mapping>

6。审查项目结构

Hibernate的一个多XML的映射项目结构

请注意,我们已经使用SET映射与各部门的员工。一个<SET>不同之处在于,它可以只存储唯一的对象。这意味着没有重复的元素可以包含在一组。当您添加第二次一套相同的元素,它将会取代旧的。一组是无序的,但默认情况下,我们可以要求它进行排序。在Java中的一个<SET>的相应类型的java.util.Set映射

执行<SET>的例子

文件:Main.java文件

package net.viralpatel.hibernate; import org.hibernate.Session;import org.hibernate.SessionFactory; public class Main {     public static void main(String[] args) {         SessionFactory sf = HibernateUtil.getSessionFactory();        Session session = sf.openSession();        session.beginTransaction();         Department department = new Department();        department.setDepartmentName("Sales");        session.save(department);         Employee emp1 = new Employee("Nina", "Mayers", "1212");        Employee emp2 = new Employee("Tony", "Almeida", "4343");         emp1.setDepartment(department);        emp2.setDepartment(department);         session.save(emp1);        session.save(emp2);         session.getTransaction().commit();        session.close();    }}

输出:

Hibernate: insert into DEPARTMENT (DEPT_NAME) values (?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)

7。到许多<bag>的例子

在一个<bag>是一个无序的集合,它可以包含重复的元素。这意味着,如果你坚持一个袋子一些元素的顺序,你不能指望以相同的顺序检索集合时保留。没有一个“œbagâ在Java集合框架的概念,所以我们只需使用一个的java.util.List的相对应的一个<bag>。

为了实现包在一个一对多的映射示例中,我们将做以下修改:

7.1更新处模型类

文件“:Department.java”

package net.viralpatel.hibernate;import java.util.ArrayList;import java.util.List;public class Department {private Long departmentId;private String departmentName;private List<Employee> employees;// Getter and Setter methods}

7.2更新XML映射

文件“:Department.hbm.xml”

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="net.viralpatel.hibernate">    <class name="Department" table="DEPARTMENT"> <id name="departmentId" type="java.lang.Long" column="DEPARTMENT_ID" ><generator class="native" /></id>        <property name="departmentName" column="DEPT_NAME"/><bag name="employees" table="employee" inverse="true" lazy="true" fetch="select">            <key>                <column name="employee_id" not-null="true" />            </key>            <one-to-many class="net.viralpatel.hibernate.Employee" />        </bag>                </class></hibernate-mapping>

7.3执行<bag>例如

执行相同的Main.java文件,在上面的例子中,我们创建了。

输出:

Hibernate: insert into DEPARTMENT (DEPT_NAME) values (?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone, department_id) values (?, ?, ?, ?, ?)


8。到许多<LIST>例如

使用<list>是一个索引集合的索引也将被保存。这意味着我们可以保留时,检索列表中的顺序。,它不同于<bag>为持续的元素的指数而<bag>不不。在Java中使用<list>相应类型的java.util.List的。

为了实现我们的一个一对多的映射示例列表中,我们将做如下变化:

8.1添加索引列的雇员表

DROP TABLE if exists `employee`;CREATE TABLE `employee` (`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,`firstname` VARCHAR(50) NULL DEFAULT NULL,`lastname` VARCHAR(50) NULL DEFAULT NULL,`birth_date` DATE NULL DEFAULT NULL,`cell_phone` VARCHAR(15) NULL DEFAULT NULL,`department_id` BIGINT(20) NULL DEFAULT NULL,`idx` INT(11) NOT NULL DEFAULT '0',PRIMARY KEY (`employee_id`),INDEX `FK_DEPT` (`department_id`),CONSTRAINT `FK_DEPT` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`))COLLATE='latin1_swedish_ci'ENGINE=InnoDBROW_FORMAT=DEFAULT

请注意,在我们现有的employee表中,我们添加了一个新列“idxâ存储每个记录的索引值。

8.2更新模型对象

文件“:Department.java”

package net.viralpatel.hibernate;import java.util.List;public class Department {private Long departmentId;private String departmentName;private List<Employee> employees;// Getter and Setter methods}

8.3更新XML映射

文件“:Department.hbm.xml”

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="net.viralpatel.hibernate">    <class name="Department" table="DEPARTMENT"> <id name="departmentId" type="java.lang.Long" column="DEPARTMENT_ID"> <generator class="native" /> </id>        <property name="departmentName" column="DEPT_NAME"/><list name="employees" table="employee" inverse="false" cascade="all">            <key column="department_id"  />    <list-index column="idx" />            <one-to-many class="net.viralpatel.hibernate.Employee" />        </list></class></hibernate-mapping>

在上面的Hibernate映射XML文件,注意,我们已经加入列表标签映射与各部门的员工列表。一个新的索引列“œidxâ是指将存储记录的索引。需要注意的是逆=“€falseâ中指定的映射,这使得作为关系雇主署。因此,时部保存对象时,它会自动保存雇员。这是必需的,这样的部门可以管理员工的索引值。DEPARTMENT_ID键列。

8.4执行<LIST>例如

输出:

Hibernate: insert into DEPARTMENT (DEPT_NAME) values (?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone) values (?, ?, ?, ?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone) values (?, ?, ?, ?)Hibernate: update EMPLOYEE set department_id=?, idx=? where EMPLOYEE_ID=?Hibernate: update EMPLOYEE set department_id=?, idx=? where EMPLOYEE_ID=?


一到多列表结果


9。到许多<array>的例子

一个<array>有相同的用法除了作为<LIST>的对应于Java中的数组类型,而不是一个java.util.List。这是很少使用,除非我们为传统应用程序映射。在大多数情况下,我们应该使用<LIST>。这是因为一个数组的大小不能被增加或减少动态的,在那里作为一个列表。

实现数组中的一个一对多的映射示例中,我们将做以下修改:

9.1更新模型对象

文件“:Department.java”

package net.viralpatel.hibernate;public class Department {private Long departmentId;private String departmentName;private Employee[] employees;// Getter and Setter methods}

我们简单地改变员工名单员工[]数组

9.2更新XML映射

文件“:Department.hbm.xml”

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="net.viralpatel.hibernate">    <class name="Department" table="DEPARTMENT"> <id name="departmentId" type="java.lang.Long" column="DEPARTMENT_ID"> <generator class="native" /> </id>        <property name="departmentName" column="DEPT_NAME"/><array name="employees" table="employee" inverse="false" cascade="all">                      <key column="department_id"  />   <list-index column="idx" />                      <one-to-many class="net.viralpatel.hibernate.Employee" />        </array>    </class></hibernate-mapping>

9.2执行<array>的例子

执行相同的Main.java类,我们创建了,在上述<LIST>例如

输出:

Hibernate: insert into DEPARTMENT (DEPT_NAME) values (?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone) values (?, ?, ?, ?)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone) values (?, ?, ?, ?)Hibernate: update EMPLOYEE set department_id=?, idx=? where EMPLOYEE_ID=?Hibernate: update EMPLOYEE set department_id=?, idx=? where EMPLOYEE_ID=?
如果你有兴趣可以阅读:Hibernate的一对一映射教程  或更多相关教程: http://www.software8.co/wzjs/PHPshili/