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>


