hibernate 實例
讓我們看一個獨立應用程序利用 hibernate 提供 java 持久性的例子。
我們將通過不同的步驟使用 hibernate 技術創建 java 應用程序。
創建 pojo 類
創建應用程序的第一步就是建立 java 的 pojo 類或者其它類,這取決于即將要存放在數據庫中的應用程序。我們可以考慮一下讓我們的 employee
類使用 getxxx
和 setxxx
方法從而使它們變成符合 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>
你需要將映射文檔以<classname>.hbm.xml
的格式保存在一個文件中。我們將映射文檔保存在 employee.hbm.xml文件中。下面讓我們看看映射文檔相關的一些小細節:
- 映射文檔是一個 xml 格式的文檔,它擁有
<hibernate-mapping>
作為根元素,這個元素包含了所有的<class>
元素。 <class>
元素被用來定義從 java 類到數據庫表的特定的映射。java 類的名稱是特定的,它使用的是類元素的name
屬性,數據庫表的名稱也是特定的,它使用的是table
屬性。<meta>
元素是一個可選元素,它可以用來創建類的描述。<id>
元素向數據庫的主要關鍵字表映射類中的特定的 id 屬性。id
元素的name
屬性涉及到了類中的屬性同時column
屬性涉及到了數據庫表中的列。type
屬性掌握了 hibernate 的映射類型,這種映射類型將會從 java 轉到 sql 數據類型。id
元素中的<generator>
元素是用來自動產生主要關鍵字的值的。將generator
元素的class
屬性設置成native
從而使 hibernate 運用identity
,sequence
或者hilo
算法依靠基礎數據庫的性能來創建主要關鍵字。<property>
元素是用來映射一個 java 類的屬性到數據庫的表中的列中。這個元素的name
屬性涉及到類中的屬性,column
屬性涉及到數據表中的列。type
屬性控制 hibernate 的映射類型,這種映射類型將會從java
轉到sql
數據類型。
映射文檔中還有許多其它的屬性和元素,在探討其它的 hibernate 相關的話題時我將會詳細進行講解。
創建應用程序類
最后,我們將要使用 main()
方法創建應用程序類來運行應用程序。我們將用這個程序來保存一些 employee 的記錄,然后我們將在這些記錄上應用 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>