📅  最后修改于: 2020-11-16 06:59:26             🧑  作者: Mango
现在让我们举一个例子来了解我们如何使用Hibernate在独立的应用程序中提供Java持久性。我们将经历使用Hibernate技术创建Java应用程序所涉及的不同步骤。
创建应用程序的第一步是构建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如何将已定义的一个或多个类映射到数据库表。
This class contains the employee detail.
您应该将映射文档保存为格式为
映射文档是一个XML文档,其中
元素是可选元素,可用于创建类描述。
id元素中的
还有其他可用的属性和元素,它们将在映射文档中使用,在讨论其他与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>