举例讲解Java的Hibernate框架中的多对一和一对多映射
投稿:goldensun
多对一(Many-to-One)映射
多对一(many-to-one)关联是最常见的关联关系,其中一个对象可以与多个对象相关联。例如,一个相同的地址对象可以与多个雇员的对象相关联。
定义RDBMS表:
考虑一个情况,我们需要员工记录存储在EMPLOYEE表,将有以下结构:
create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, address INT NOT NULL, PRIMARY KEY (id) );
此外,许多员工都可以有相同的地址,所以这种关联可以使用许多一对一的关联呈现。我们将存储地址相关的信息在一个单独的表,该表具有以下结构:
create table ADDRESS ( id INT NOT NULL auto_increment, street_name VARCHAR(40) default NULL, city_name VARCHAR(40) default NULL, state_name VARCHAR(40) default NULL, zipcode VARCHAR(10) default NULL, PRIMARY KEY (id) );
同时创建RBDMS表,并让他们准备下一个实现。
定义POJO类:
让我们实现一个POJO类员工将被用于保存与EMPLOYEE表的对象和其地址类型的变量。
import java.util.*;
public class Employee{
  private int id;
  private String firstName; 
  private String lastName;  
  private int salary;
  private Address address;
  public Employee() {}
  public Employee(String fname, String lname, 
          int salary, Address address ) {
   this.firstName = fname;
   this.lastName = lname;
   this.salary = salary;
   this.address = address;
  }
  public int getId() {
   return id;
  }
  public void setId( int id ) {
   this.id = id;
  }
  public String getFirstName() {
   return firstName;
  }
  public void setFirstName( String first_name ) {
   this.firstName = first_name;
  }
  public String getLastName() {
   return lastName;
  }
  public void setLastName( String last_name ) {
   this.lastName = last_name;
  }
  public int getSalary() {
   return salary;
  }
  public void setSalary( int salary ) {
   this.salary = salary;
  }
  public Address getAddress() {
   return address;
  }
  public void setAddress( Address address ) {
   this.address = address;
  }
}
我们需要定义相应的地址表,这样地址对象可以存储和检索到地址表中的另一个POJO类。
import java.util.*;
public class Address{
  private int id;
  private String street;   
  private String city;   
  private String state;  
  private String zipcode; 
  public Address() {}
  public Address(String street, String city, 
         String state, String zipcode) {
   this.street = street; 
   this.city = city; 
   this.state = state; 
   this.zipcode = zipcode; 
  }
  public int getId() {
   return id;
  }
  public void setId( int id ) {
   this.id = id;
  }
  public String getStreet() {
   return street;
  }
  public void setStreet( String street ) {
   this.street = street;
  }
  public String getCity() {
   return city;
  }
  public void setCity( String city ) {
   this.city = city;
  }
  public String getState() {
   return state;
  }
  public void setState( String state ) {
   this.state = state;
  }
  public String getZipcode() {
   return zipcode;
  }
  public void setZipcode( String zipcode ) {
   this.zipcode = zipcode;
  }
  
}
定义Hibernate映射文件:
开发我们的映射文件,可指示Hibernate如何定义的类映射到数据库表。<many-to-one>进行元素将被用来定义规则建立Employee和Address实体之间的多对一关系。
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
  <class name="Employee" table="EMPLOYEE">
   <meta attribute="class-description">
     This class contains the employee detail. 
   </meta>
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>
   <property name="firstName" column="first_name" type="string"/>
   <property name="lastName" column="last_name" type="string"/>
   <property name="salary" column="salary" type="int"/>
   <many-to-one name="address" column="address" 
    class="Address" not-null="true"/>
  </class>
  <class name="Address" table="ADDRESS">
   <meta attribute="class-description">
     This class contains the address detail. 
   </meta>
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>
   <property name="street" column="street_name" type="string"/>
   <property name="city" column="city_name" type="string"/>
   <property name="state" column="state_name" type="string"/>
   <property name="zipcode" column="zipcode" type="string"/>
  </class>
</hibernate-mapping>
应该保存的映射文件中的格式<classname>.hbm.xml。保存映射文件中的文件Employee.hbm.xml。已经熟悉了大部分的映射细节,但让我们再次看看映射文件中的所有元素:
映射文档是具有<hibernate-mapping>为对应于每一个类包含2个<class>元素的根元素的XML文档。
<class>元素被用于定义数据库表从一个Java类特定的映射。 Java类名指定使用class元素的name属性和使用表属性数据库表名指定。
<meta>元素是可选元素,可以用来创建类的描述。
<id>元素映射在类中的唯一ID属性到数据库表的主键。 id元素的name属性是指属性的类和column属性是指在数据库表中的列。 type属性保存了Hibernate映射类型,这种类型的映射将会从Java转换为SQL数据类型。
id元素内<generator>元素被用来自动生成的主键值。将生成元素class属性设置为原生让Hibernate拾取无论是identity,sequence或者hilo的算法来创建主键根据底层数据库的支持能力。
<property>元素用于一个Java类的属性映射到数据库表中的列。元素的name属性是指属性的类和column属性是指在数据库表中的列。 type属性保存了Hibernate映射类型,这种类型的映射将会从Java转换为SQL数据类型。
<many-to-one>进行元素是用来设置EMPLOYEE和地址的实体之间的关系。name属性被设置为在父类中定义的变量,在我们的情况下,它是地址。列属性用于在父表EMPLOYEE集的列名。
最后,我们将创建应用程序类的main()方法来运行应用程序。我们将使用这个应用程序,以节省一些employee连同的记录他们的地址,然后我们将申请CRUD操作上的记录。
import java.util.*;
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
  private static SessionFactory factory; 
  public static void main(String[] args) {
   try{
     factory = new Configuration().configure().buildSessionFactory();
   }catch (Throwable ex) { 
     System.err.println("Failed to create sessionFactory object." + ex);
     throw new ExceptionInInitializerError(ex); 
   }
   ManageEmployee ME = new ManageEmployee();
   /* Let us have one address object */
   Address address = ME.addAddress("Kondapur","Hyderabad","AP","532");
   /* Add employee records in the database */
   Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, address);
   /* Add another employee record in the database */
   Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, address);
   /* List down all the employees */
   ME.listEmployees();
   /* Update employee's salary records */
   ME.updateEmployee(empID1, 5000);
   /* Delete an employee from the database */
   ME.deleteEmployee(empID2);
   /* List down all the employees */
   ME.listEmployees();
  }
  /* Method to add an address record in the database */
  public Address addAddress(String street, String city, 
               String state, String zipcode) {
   Session session = factory.openSession();
   Transaction tx = null;
   Integer addressID = null;
   Address address = null;
   try{
     tx = session.beginTransaction();
     address = new Address(street, city, state, zipcode);
     addressID = (Integer) session.save(address); 
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
   return address;
  }
  /* Method to add an employee record in the database */
  public Integer addEmployee(String fname, String lname, 
               int salary, Address address){
   Session session = factory.openSession();
   Transaction tx = null;
   Integer employeeID = null;
   try{
     tx = session.beginTransaction();
     Employee employee = new Employee(fname, lname, salary, address);
     employeeID = (Integer) session.save(employee); 
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
   return employeeID;
  }
  /* Method to list all the employees detail */
  public void listEmployees( ){
   Session session = factory.openSession();
   Transaction tx = null;
   try{
     tx = session.beginTransaction();
     List employees = session.createQuery("FROM Employee").list(); 
     for (Iterator iterator = 
              employees.iterator(); iterator.hasNext();){
      Employee employee = (Employee) iterator.next(); 
      System.out.print("First Name: " + employee.getFirstName()); 
      System.out.print(" Last Name: " + employee.getLastName()); 
      System.out.println(" Salary: " + employee.getSalary());
      Address add = employee.getAddress();
      System.out.println("Address ");
      System.out.println(" Street: " + add.getStreet());
      System.out.println(" City: " + add.getCity());
      System.out.println(" State: " + add.getState());
      System.out.println(" Zipcode: " + add.getZipcode());
     }
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
  }
  /* Method to update salary for an employee */
  public void updateEmployee(Integer EmployeeID, int salary ){
   Session session = factory.openSession();
   Transaction tx = null;
   try{
     tx = session.beginTransaction();
     Employee employee = 
          (Employee)session.get(Employee.class, EmployeeID); 
     employee.setSalary( salary );
     session.update(employee);
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
  }
  /* Method to delete an employee from the records */
  public void deleteEmployee(Integer EmployeeID){
   Session session = factory.openSession();
   Transaction tx = null;
   try{
     tx = session.beginTransaction();
     Employee employee = 
          (Employee)session.get(Employee.class, EmployeeID); 
     session.delete(employee); 
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
  }
}
编译和执行:
下面是步骤来编译并运行上述应用程序。请确保已在进行的编译和执行之前,适当地设置PATH和CLASSPATH。
- 创建hibernate.cfg.xml配置文件中配置章节解释。
 - 创建Employee.hbm.xml映射文件,如上图所示。
 - 创建Employee.java源文件,如上图所示,并编译它。
 - 创建Address.java源文件,如上图所示,并编译它。
 - 创建ManageEmployee.java源文件,如上图所示,并编译它。
 - 执行ManageEmployee二进制文件来运行程序。
 
在屏幕上获得以下结果,并同时记录会在员工和地址表创建。
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Manoj Last Name: Kumar Salary: 4000
Address
    Street: Kondapur
    City: Hyderabad
    State: AP
    Zipcode: 532
First Name: Dilip Last Name: Kumar Salary: 3000
Address
    Street: Kondapur
    City: Hyderabad
    State: AP
    Zipcode: 532
First Name: Manoj Last Name: Kumar Salary: 5000
Address
    Street: Kondapur
    City: Hyderabad
    State: AP
    Zipcode: 532
如果检查员工和地址表,就应该记录下了:
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+---------+ | id | first_name | last_name | salary | address | +----+------------+-----------+--------+---------+ | 1 | Manoj | Kumar | 5000 | 5 | +----+------------+-----------+--------+---------+ 1 row in set (0.00 sec)
mysql> select * from ADDRESS;
+----+-------------+-----------+------------+---------+ | id | street_name | city_name | state_name | zipcode | +----+-------------+-----------+------------+---------+ | 1 | Kondapur | Hyderabad | AP | 532 | +----+-------------+-----------+------------+---------+ 1 row in set (0.00 sec)
一对多(One-to-Many)映射
一对多的映射可以使用一组Java集合不包含任何重复的元素来实现。我们已经看到了如何设置映射集合在Hibernate中,所以如果你已经学会了集合(Set)映射,那么所有设置可用于一对多的映射。
集合被映射到与映射表中<set>元素,并java.util.HashSet中初始化。您可以使用Set集合在类中,有一个集合中不需要重复的元素。
RDBMS表与POJO类我们依然采用上面例子中定义好的,
定义Hibernate映射文件:
让我们指示Hibernate如何定义的类映射到数据库表的映射文件。
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
  <class name="Employee" table="EMPLOYEE">
   <meta attribute="class-description">
     This class contains the employee detail. 
   </meta>
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>
   <set name="certificates" cascade="all">
     <key column="employee_id"/>
     <one-to-many class="Certificate"/>
   </set>
   <property name="firstName" column="first_name" type="string"/>
   <property name="lastName" column="last_name" type="string"/>
   <property name="salary" column="salary" type="int"/>
  </class>
  <class name="Certificate" table="CERTIFICATE">
   <meta attribute="class-description">
     This class contains the certificate records. 
   </meta>
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>
   <property name="name" column="certificate_name" type="string"/>
  </class>
</hibernate-mapping>
应该保存的映射文件中的格式<classname>.hbm.xml。我们保存映射文件中的文件Employee.hbm.xml。你已经熟悉了大部分的映射细节,但让我们再次看看映射文件中的所有元素:
映射文档是具有<hibernate-mapping>为对应于每一个类包含2个<class>元素的根元素的XML文档。
<class>元素被用于定义数据库表从一个Java类特定的映射。 Java类名指定使用class元素的name属性和使用表属性数据库表名指定。
<meta>元素是可选元素,可以用来创建类的描述。
<id>元素映射在类中的唯一ID属性到数据库表的主键。 id元素的name属性是指属性的类和column属性是指在数据库表中的列。 type属性保存了Hibernate映射类型,这种类型的映射将会从Java转换为SQL数据类型。
id元素内的<generator>元素被用来自动生成的主键值。将生成元素的class属性设置为原生让Hibernate拾取identity,sequence或者hilo中的算法来创建主键根据底层数据库的支持能力。
<property>元素用于一个Java类的属性映射到数据库表中的列。元素的name属性是指属性的类和column属性是指在数据库表中的列。 type属性保存了Hibernate映射类型,这种类型的映射将会从Java转换为SQL数据类型。
<set>元素设置证书和Employee类之间的关系。我们使用cascade属性中<set>元素来告诉Hibernate来保存证书的对象,同时为Employee对象。 name属性被设置为在父类中定义的变量集,在我们的例子是证书。对于每一组变量,我们需要定义在映射文件中单独的一组元素。
<key>元素是包含外键的父对象,即在证书表中的列。表EMPLOYEE。
<one-to-many>元素表示一个Employee对象涉及到很多证书的对象。
创建应用程序类:
最后,我们将创建应用程序类的main()方法来运行应用程序。我们将使用这个应用程序,以节省一些员工连同记录证书,然后我们将应用上CRUD操作记录。
import java.util.*;
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
  private static SessionFactory factory; 
  public static void main(String[] args) {
   try{
     factory = new Configuration().configure().buildSessionFactory();
   }catch (Throwable ex) { 
     System.err.println("Failed to create sessionFactory object." + ex);
     throw new ExceptionInInitializerError(ex); 
   }
   ManageEmployee ME = new ManageEmployee();
   /* Let us have a set of certificates for the first employee */
   HashSet set1 = new HashSet();
   set1.add(new Certificate("MCA"));
   set1.add(new Certificate("MBA"));
   set1.add(new Certificate("PMP"));
   
   /* Add employee records in the database */
   Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
   /* Another set of certificates for the second employee */
   HashSet set2 = new HashSet();
   set2.add(new Certificate("BCA"));
   set2.add(new Certificate("BA"));
   /* Add another employee record in the database */
   Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
   /* List down all the employees */
   ME.listEmployees();
   /* Update employee's salary records */
   ME.updateEmployee(empID1, 5000);
   /* Delete an employee from the database */
   ME.deleteEmployee(empID2);
   /* List down all the employees */
   ME.listEmployees();
  }
  /* Method to add an employee record in the database */
  public Integer addEmployee(String fname, String lname, 
                      int salary, Set cert){
   Session session = factory.openSession();
   Transaction tx = null;
   Integer employeeID = null;
   try{
     tx = session.beginTransaction();
     Employee employee = new Employee(fname, lname, salary);
     employee.setCertificates(cert);
     employeeID = (Integer) session.save(employee); 
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
   return employeeID;
  }
  /* Method to list all the employees detail */
  public void listEmployees( ){
   Session session = factory.openSession();
   Transaction tx = null;
   try{
     tx = session.beginTransaction();
     List employees = session.createQuery("FROM Employee").list(); 
     for (Iterator iterator1 = 
              employees.iterator(); iterator1.hasNext();){
      Employee employee = (Employee) iterator1.next(); 
      System.out.print("First Name: " + employee.getFirstName()); 
      System.out.print(" Last Name: " + employee.getLastName()); 
      System.out.println(" Salary: " + employee.getSalary());
      Set certificates = employee.getCertificates();
      for (Iterator iterator2 = 
             certificates.iterator(); iterator2.hasNext();){
         Certificate certName = (Certificate) iterator2.next(); 
         System.out.println("Certificate: " + certName.getName()); 
      }
     }
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
  }
  /* Method to update salary for an employee */
  public void updateEmployee(Integer EmployeeID, int salary ){
   Session session = factory.openSession();
   Transaction tx = null;
   try{
     tx = session.beginTransaction();
     Employee employee = 
          (Employee)session.get(Employee.class, EmployeeID); 
     employee.setSalary( salary );
     session.update(employee);
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
  }
  /* Method to delete an employee from the records */
  public void deleteEmployee(Integer EmployeeID){
   Session session = factory.openSession();
   Transaction tx = null;
   try{
     tx = session.beginTransaction();
     Employee employee = 
          (Employee)session.get(Employee.class, EmployeeID); 
     session.delete(employee); 
     tx.commit();
   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
   }finally {
     session.close(); 
   }
  }
}
编译和执行:
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MBA Certificate: PMP Certificate: MCA
如果检查员工和证书表,就应该记录下了:
mysql> select * from employee;
+----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec)
mysql> select * from certificate;
+----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0.00 sec)
