Hibernate是一个持久层的ORM框架,主要用于DAO层,即管理Java 应用程序与关系型数据库的交互。
ORM(Object Relation Mapping)就是利用描述对象和数据库表之间映射的元数据,自动把Java应用程序中的对象,持久化到关系型数据库的表中。对于一个大型的项目,写很多条JDBC的sql语句是十分复杂且难以管理的,于是ORM利用描述对象和数据库表之间映射的元数据,自动把Java应用程序中的对象,持久化到关系型数据库的表中。
一、基础配置方式
1. XML 配置(hibernate.cfg.xml)
<!-- src/main/resources/hibernate.cfg.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接设置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- SQL 方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- 开发环境配置 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射文件 -->
<mapping class="com.example.Employee"/>
<mapping resource="com/example/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2. Java 属性文件配置(hibernate.properties)
# src/main/resources/hibernate.properties
hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/testdb
hibernate.connection.username=root
hibernate.connection.password=123456
hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
3. 纯 Java 代码配置
Configuration configuration = new Configuration()
.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver")
.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/testdb")
.setProperty("hibernate.connection.username", "root")
.setProperty("hibernate.connection.password", "123456")
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect")
.addAnnotatedClass(Employee.class)
.addResource("com/example/Product.hbm.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
二、Hibernate持久化类
Hibernate 中的对象有四种状态:
-
瞬时态(Transient):刚创建,未与 Session 关联
-
持久态(Persistent):已与 Session 关联,有 OID
-
游离态(Detached):曾经持久化,但 Session 已关闭
-
删除态(Removed):被标记为删除,但未从数据库删除
@Test
public void testStateTransitionWithSave() {
// 获取Session和开启事务
// HibernateUtils为自己封装,由于sessionFactory使用工厂模式,一个项目就开一个实例就好了
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
try {
// 1. 创建瞬时态对象 - 无OID,未被Session管理
Customer customer = new Customer();
customer.setName("张三");
customer.setEmail("zhangsan@example.com");
System.out.println("瞬时态对象 - ID: " + customer.getId()); // null
// 2. 转换为持久态 - 调用save()方法
Serializable id = session.save(customer); // 返回生成的ID
System.out.println("持久态对象 - ID: " + customer.getId()); // 有值
// 3. 持久态对象的特性演示
// 修改会被自动同步到数据库(脏检查)
customer.setName("张三丰");
// 可以直接通过Session查询
Customer persistedCustomer = session.get(Customer.class, id);
System.out.println("查询结果: " + persistedCustomer.getName());
tx.commit(); // 事务提交时,所有变更同步到数据库
// 4. 转换为游离态 - Session关闭后
session.close();
System.out.println("游离态对象 - ID: " + customer.getId()); // ID仍在
customer.setEmail("new@example.com"); // 修改不会自动同步到数据库
} catch (Exception e) {
if (tx != null) tx.rollback();
throw e;
} finally {
if (session != null && session.isOpen()) {
// 一般在所有项目结束时才关闭session
session.close();
}
}
}
三、Hibernate 一级缓存
Hibernate框架中提供了很多种优化手段,其中包括缓存和抓取策略。仅从缓存来说,Hibernate提供了二种缓存机制,分别为:
一级缓存:Hibernate的一级缓存又被称为是Session级别的缓存,一级缓存的生命周期与Session一致,也就是说Session创建了,一级缓存也就存在了,因为一级缓存是由Session中一系列的Java集合构成的,而且一级缓存是自带的、不可卸载的;
二级缓存:Hibernate的二级缓存是SessionFactory级别的缓存,需要手动进行配置,默认是不开启的。二级缓存在企业开发中基本上已经不用了,因为我们一般都会用Redis,Redis就可以替代Hibernate的二级缓存。
// 如果session中存在则直接返回session中的值,没有则发送一条sql查询语句去查询
Server server = session.get(Server.class, 1l);
参考博客: