目录

Hibernate - 例子

现在让我们举个例子来了解我们如何使用Hibernate在独立应用程序中提供Java持久性。 我们将介绍使用Hibernate技术创建Java应用程序所涉及的不同步骤。

创建POJO类

创建应用程序的第一步是构建Java POJO类或类,具体取决于将持久保存到数据库的应用程序。 让我们考虑使用getXXXsetXXX方法的Employee类,使其成为JavaBeans兼容类。

POJO(Plain Old Java Object)是一个Java对象,它不扩展或实现EJB框架分别需要的某些专用类和接口。 所有普通的Java对象都是POJO。

当您设计一个由Hibernate持久化的类时,提供符合JavaBeans的代码以及一个属性非常重要,这些属性在Employee类中将作为id属性的索引使用。

public class Employee {
   private int id;
   private String firstName; 
   private String lastName;   
   private int salary;  
   public Employee() {}
   public Employee(String fname, String lname, int salary) {
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
   }
   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;
   }
}

创建数据库表

第二步是在数据库中创建表。 每个对象都会有一个表,您愿意提供持久性。 考虑上面的对象需要存储和检索到以下RDBMS表中 -

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,
   PRIMARY KEY (id)
);

创建映射配置文件

这一步是创建一个映射文件,指示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>
      <property name = "firstName" column = "first_name" type = "string"/>
      <property name = "lastName" column = "last_name" type = "string"/>
      <property name = "salary" column = "salary" type = "int"/>
   </class>
</hibernate-mapping>

您应该将映射文档保存在格式为 .hbm.xml的文件中。 我们将映射文档保存在Employee.hbm.xml文件中。 让我们看一下有关映射文档的细节 -

  • 映射文档是一个XML文档,其中作为包含所有元素的根元素。

  • 《class》元素用于定义从Java类到数据库表的特定映射。 使用class元素的name属性指定Java类名,并使用table属性指定数据库表名。

  • 《meta》元素是可选元素,可用于创建类描述。

  • 《id》元素将类中的唯一ID属性映射到数据库表的主键。 id元素的name属性引用类中的属性, column属性引用数据库表中的列。 type属性包含hibernate映射类型,这种映射类型将从Java转换为SQL数据类型。

  • id元素中的《generator》元素用于自动生成主键值。 生成器元素的class属性设置为native ,让hibernate选择identity, sequencehilo算法来创建主键,具体取决于底层数据库的功能。

  • 《property》元素用于将Java类属性映射到数据库表中的列。 元素的name属性引用类中的属性, column属性引用数据库表中的列。 type属性包含hibernate映射类型,这种映射类型将从Java转换为SQL数据类型。

还有其他可用的属性和元素,这些属性和元素将用于映射文档中,我将尝试在讨论其他Hibernate相关主题时尽可能多地介绍它们。

创建应用程序类 (Create Application Class)

最后,我们将使用main()方法创建应用程序类来运行应用程序。 我们将使用此应用程序来保存很少的员工记录,然后我们将对这些记录应用CRUD操作。

import java.util.List; 
import java.util.Date;
import java.util.Iterator; 
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();
      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);
      /* List down all the employees */
      ME.listEmployees();
      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);
      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);
      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try {
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      } catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      } finally {
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   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()); 
         }
         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(); 
      }
   }
}

编译和执行 (Compilation and Execution)

以下是编译和运行上述应用程序的步骤。 确保在进行编译和执行之前已适当地设置了PATH和CLASSPATH。

  • 按配置章节中的说明创建hibernate.cfg.xml配置文件。

  • 创建Employee.hbm.xml映射文件,如上所示。

  • 如上所示创建Employee.java源文件并进行编译。

  • 创建ManageEmployee.java源文件,如上所示并编译它。

  • 执行ManageEmployee二进制文件以运行该程序。

您将获得以下结果,并且将在EMPLOYEE表中创建记录。

$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Zara  Last Name: Ali  Salary: 1000
First Name: Daisy  Last Name: Das  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000

如果您检查您的EMPLOYEE表,它应该有以下记录 -

mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 29 | Zara       | Ali       |   5000 |
| 31 | John       | Paul      |  10000 |
+----+------------+-----------+--------+
2 rows in set (0.00 sec
mysql>
↑回到顶部↑
WIKI教程 @2018