讓我們看一個獨立應(yīng)用程序利用 Hibernate 提供 Java 持久性的例子。我們將通過不同的步驟使用 Hibernate 技術(shù)創(chuàng)建 Java 應(yīng)用程序。
創(chuàng)建應(yīng)用程序的第一步就是建立 Java 的 POJO 類或者其它類,這取決于即將要存放在數(shù)據(jù)庫中的應(yīng)用程序。我們可以考慮一下讓我們的 Employee 類使用 getXXX 和 setXXX 方法從而使它們變成符合 JavaBeans 的類。
POJO (Plain Old Java Object) 是 Java 的一個對象,這種對象不會擴展或者執(zhí)行一些特殊的類并且它的接口都是分別在 EJB 框架的要求下的。所有正常的 Java 對象都是 POJO。
當你設(shè)計一個存放在 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;
}
}
第二步就是在你的數(shù)據(jù)庫中創(chuàng)建表格。每一個你所愿意提供長期留存的對象都會有一個對應(yīng)的表。上述的對象需要在下列的 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)
);
這一步是創(chuàng)建一個映射文件從而指導 Hibernate 如何對數(shù)據(jù)庫的表映射定義的類。
<?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
文件中。下面讓我們看看映射文檔相關(guān)的一些小細節(jié):
<hibernate-mapping>
作為根元素,這個元素包含了所有的 <class>
元素。 <class>
元素被用來定義從 Java 類到數(shù)據(jù)庫表的特定的映射。Java 類的名稱是特定的,它使用的是類元素的 name 屬性,數(shù)據(jù)庫表的名稱也是特定的,它使用的是 table 屬性。 <meta>
元素是一個可選元素,它可以用來創(chuàng)建類的描述。 <id>
元素向數(shù)據(jù)庫的主要關(guān)鍵字表映射類中的特定的 ID 屬性。id 元素的 name 屬性涉及到了類中的屬性同時 column 屬性涉及到了數(shù)據(jù)庫表中的列。type 屬性掌握了 hibernate 的映射類型,這種映射類型將會從 Java 轉(zhuǎn)到 SQL 數(shù)據(jù)類型。 <generator>
元素是用來自動產(chǎn)生主要關(guān)鍵字的值的。將 generator 元素的 class 屬性設(shè)置成 native 從而使 Hibernate 運用 identity, sequence 或者 hilo 算法依靠基礎(chǔ)數(shù)據(jù)庫的性能來創(chuàng)建主要關(guān)鍵字。 <property>
元素是用來映射一個 Java 類的屬性到數(shù)據(jù)庫的表中的列中。這個元素的 name 屬性涉及到類中的屬性,column 屬性涉及到數(shù)據(jù)表中的列。type 屬性控制 Hibernate 的映射類型,這種映射類型將會從 Java 轉(zhuǎn)到 SQL 數(shù)據(jù)類型。 映射文檔中還有許多其它的屬性和元素,在探討其它的 Hibernate 相關(guān)的話題時我將會詳細進行講解。
最后,我們將要使用 main() 方法創(chuàng)建應(yīng)用程序類來運行應(yīng)用程序。我們將用這個程序來保存一些 Employee 的記錄,然后我們將在這些記錄上應(yīng)用 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();
}
}
}
下面是編譯和運行上述提到的應(yīng)用程序的步驟。在編譯和執(zhí)行應(yīng)用程序之前確保你已經(jīng)設(shè)置好了 PATH 和 CLASSPATH。
你將會得到如下結(jié)果,記錄將會在 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>
更多建議: