- Hibernate教程
- Hibernate - 主页
- ORM - 概述
- Hibernate - 概述
- Hibernate - 架构
- Hibernate - 环境
- Hibernate - 配置
- Hibernate - 会话
- Hibernate - 持久类
- Hibernate - 映射文件
- Hibernate - 映射类型
- Hibernate - 示例
- Hibernate - O/R 映射
- Hibernate - 注释
- Hibernate - 查询语言
- Hibernate - 标准查询
- Hibernate - 原生 SQL
- Hibernate - 缓存
- Hibernate - 批处理
- Hibernate - 拦截器
- Hibernate 有用资源
- Hibernate - 问题与解答
- Hibernate - 快速指南
- Hibernate - 有用的资源
- Hibernate - 讨论
Hibernate - 示例
现在让我们通过一个示例来了解如何使用 Hibernate 在独立应用程序中提供 Java 持久性。我们将介绍使用 Hibernate 技术创建 Java 应用程序所涉及的不同步骤。
创建 POJO 类
创建应用程序的第一步是构建一个或多个 Java POJO 类,具体取决于将保存到数据库的应用程序。让我们考虑使用getXXX和setXXX方法的Employee类,使其成为 JavaBeans 兼容类。
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> 作为根元素的 XML 文档,其中包含所有 <class> 元素。
<class>元素用于定义从 Java 类到数据库表的特定映射。Java 类名使用class 元素的name属性指定,数据库表名使用table属性指定。
<meta>元素是可选元素,可用于创建类描述。
<id> 元素将类中的唯一 ID 属性映射到数据库表的主键。id元素的name属性指的是类中的属性,column属性指的是数据库表中的列。type属性保存hibernate映射类型,该映射类型将从Java转换为SQL数据类型。
id 元素中的<generator>元素用于自动生成主键值。生成器元素的class属性设置为native,以便让 hibernate 选择标识、序列或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>