发布于 2015-07-28 15:17:24 | 419 次阅读 | 评论: 0 | 来源: 网络整理

我们尝试使用Hibernate提供的一个独立应用程序Java持久化例子。通过使用Hibernate技术创建Java应用程序,步骤如下:

创建POJO 类:

在创建应用程序的第一步是建立在Java POJO类或类,具体取决于将被持久化到数据库的应用程序。让我们考虑我们的Employee类的getXXX和setXXX方法,使其兼容JavaBean类。 

POJO(普通Java对象)是一个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>

应该保存的映射文件中的格式<classname>.hbm.xml。我们保存我们的映射文件中的文件Employee.hbm.xml。让我们来看看有关映射文件的小细节:

  • 映射文档是具有<hibernate-mapping>为包含所有的<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数据类型。

还有这将在映射文件中使用,我会尽量覆盖尽可能多的在讨论其他的Hibernate相关主题的其他属性和可用的元素。

创建应用程序类:

最后,我们将创建应用程序类 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(); 
      }
   }
}

编译和执行:

下面是步骤来编译并运行上述应用程序。请确保已在进行的编译和执行之前,适当地设置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>
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务