Hibernate 是一个开源的对象关系映射(ORM)框架,用于简化 Java 应用程序与关系数据库之间的数据持久化。它将 Java 类映射到数据库表,将 Java 对象的属性映射到表中的列,从而实现对象与关系数据库之间的自动映射与转换。Hibernate 以透明、简洁且高效的方式处理持久化数据,极大地减少了开发者的工作量。
核心概念
- Session: 用于执行 CRUD 操作的接口,是 Hibernate 与数据库之间的交互接口。
- SessionFactory: 用于创建 Session 对象的工厂。
- Configuration: 配置对象,用于加载 Hibernate 配置文件和映射文件。
- Transaction: 表示数据库事务,用于确保数据操作的完整性和一致性。
- Query: 用于执行 HQL(Hibernate Query Language)或 SQL 查询的接口。
配置
- Hibernate Configuration File (
hibernate.cfg.xml): 用于配置数据库连接属性和 Hibernate 相关设置。
xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yourdb</property>
<property name="hibernate.connection.username">yourusername</property>
<property name="hibernate.connection.password">yourpassword</property>
<!-- JDBC connection pool settings -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="path/to/yourmappingfile.hbm.xml"/>
</session-factory>
</hibernate-configuration>
- Entity Class: Java 类映射到数据库表。
java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Employee")
public class Employee {
@Id
private int id;
private String name;
private String department;
private double salary;
// Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
- DAO (Data Access Object): 数据库操作的实现类。
java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeeDAO {
private static SessionFactory factory;
static {
// Create the SessionFactory from hibernate.cfg.xml
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public void addEmployee(Employee employee) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(employee);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public Employee getEmployee(int id) {
Session session = factory.openSession();
Employee employee = null;
try {
employee = session.get(Employee.class, id);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return employee;
}
public void updateEmployee(Employee employee) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(employee);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void deleteEmployee(int id) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = session.get(Employee.class, id);
if (employee != null) {
session.delete(employee);
tx.commit();
}
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
- Main Class: 测试 DAO 操作。
java
public class HibernateExample {
public static void main(String[] args) {
EmployeeDAO employeeDAO = new EmployeeDAO();
// Add Employee
Employee emp = new Employee();
emp.setId(1);
emp.setName("John Doe");
emp.setDepartment("Engineering");
emp.setSalary(75000);
employeeDAO.addEmployee(emp);
// Get Employee
Employee retrievedEmp = employeeDAO.getEmployee(1);
System.out.println("Retrieved Employee: " + retrievedEmp.getName());
// Update Employee
retrievedEmp.setSalary(80000);
employeeDAO.updateEmployee(retrievedEmp);
// Delete Employee
employeeDAO.deleteEmployee(1);
}
}
详细解释
-
配置文件 :
hibernate.cfg.xml配置文件定义了数据库连接属性、JDBC 连接池设置、SQL 方言以及映射文件路径。这个文件是 Hibernate 的核心配置文件,通常放在资源目录下。 -
实体类 :
Employee类使用@Entity注解标识为 Hibernate 实体类,@Table注解定义了该类对应的数据库表名。类的字段映射到表的列,使用@Id注解定义主键字段。 -
DAO 类 :
EmployeeDAO类包含了基本的 CRUD 操作方法,包括添加、获取、更新和删除员工记录。使用SessionFactory创建Session对象,使用Transaction处理数据库事务,确保数据一致性。 -
测试类 :
HibernateExample类通过EmployeeDAO调用 CRUD 操作方法,演示了如何使用 Hibernate 进行数据库操作。
通过这些代码示例,展示了 Hibernate 的基本使用方法,包括配置、实体映射、数据访问和事务管理。Hibernate 提供了一种简洁高效的方式来处理 Java 对象与关系数据库之间的持久化操作。