现在让我们举个例子来了解我们如何使用Hibernate在独立应用程序中提供Java持久性.我们将介绍使用Hibernate技术创建Java应用程序所涉及的不同步骤.
创建应用程序的第一步是构建Java POJO类或类,具体取决于将持久保存到数据库的应用程序.让我们考虑使用 getXXX 和 setXXX 方法的 Employee 类,使其符合JavaBeans类.
POJO(Plain Old Java Object)是一个Java对象,它不扩展或实现EJB框架分别需要的某些专用类和接口.所有普通的Java对象都是POJO.
当您设计一个由Hibernate持久化的类时,提供符合JavaBeans的代码以及一个属性非常重要,这些属性可以像
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文件中.让我们看一下关于映射文档的一些细节 :
映射文档是一个XML文档,其中包含< hibernate-mapping> ;作为包含所有< class>的根元素元素.
< class> 元素用于定义从Java类到数据库表的特定映射.使用类元素的 name 属性指定Java类名,并使用表属性指定数据库表名.
< meta> 元素是可选元素,可用于创建类描述.
< id> 元素将类中的唯一ID属性映射到数据库表的主键. id元素的 name 属性引用类中的属性,列属性引用数据库表中的列. type 属性保存hibernate映射类型,此映射类型将从Java转换为SQL数据类型.
id元素中的< generator> 元素用于自动生成主键值.生成器元素的 class 属性设置为 native ,让hibernate选择标识,序列或 hilo 根据底层数据库的功能创建主键的算法.
< property> 元素用于映射a Java类属性到数据库表中的一列.元素的 name 属性引用类中的属性,列属性引用数据库表中的列. 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>