Hibernate是一款重量级的持久层框架,目前市面上的我很少见还有项目在开发时候使用他,之所以要学习这个,因为公司最近有一个系统升级的项目,之前的老系统用到了Hibernate。

同样还是老套路,学习一个新技术或者新知识,首先去他的官网看
【官网】:https://hibernate.org/orm/
【官方教程】:https://hibernate.org/orm/documentation/getting-started/
【github地址】:https://github.com/hibernate
目前hibernate已经更新到了6的版本,这里使用的5的版本

注意: Hibernate5.1;5.2官方推荐使用JDK1.8以及JDBC4
在学习Hibernate之前,我们需要回顾下ORM,我们都肯定用过或者熟悉Mybatis的,(或者有看过我之前的MyBatis的博客)。我们都知道Mybatis是一款半自动的ORM框架
ORM(Object/Relation Mapping):对象关系映射
| 面向对象概念 | 面向关系概念 |
|---|---|
| 类 | 表 |
| 对象 | 表的行(记录) |
| 属性 | 表的列(字段) |
程序员可以把对数据库的操作转化为对对象的操作采用元数据来描述对象-关系映射细节,元数据通常采用XML格式ORM思想的好处:
数据库脚本:
CREATE TABLE `t_customer` (
`c_id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`c_name` VARCHAR(20) NOT NULL DEFAULT '' COLLATE 'utf8mb4_general_ci',
`c_gender` CHAR(1) NOT NULL DEFAULT '' COMMENT '1:男 0:女' COLLATE 'utf8mb4_general_ci',
`c_age` INT(10) NOT NULL DEFAULT '0',
`c_level` VARCHAR(20) NOT NULL DEFAULT '0' COLLATE 'utf8mb4_general_ci',
PRIMARY KEY (`c_id`) USING BTREE
)
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB;
开发所需要的jar包:

说明:
geronimo-jta_1.1_spec-1.1.1.jar必须要有,否则可能会报出java.lang.NoClassDefFoundError: javax/transaction/Synchronization的异常
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String gender;
private Integer age;
private String level;
// getter、setter...
}
*.hbm.xml🔥🔥【建议规则要求】:
实体类名称.hbm.xml和实体类存放在一个目录下
DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wei.domain.Customer" table="t_customer">
<id name="id" column="c_id">
<generator class="native">generator>
id>
<property name="name" column="c_name">property>
<property name="age" column="c_age">property>
<property name="gender" column="c_gender">property>
<property name="level" column="c_level">property>
class>
hibernate-mapping>
配置文件中类的所在包generator: 主键增长生成策略
hibernate.cfg.xml🔥🔥核心配置文件主要用于配置数据库的相关链接操作
DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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.Driverproperty>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTCproperty>
<property name="hibernate.connection.username">rootproperty>
<property name="hibernate.connection.password">123456property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>
<mapping resource="com/wei/domain/Customer.hbm.xml">mapping>
session-factory>
hibernate-configuration>
一共分为三个部分:
使用标签,多个实体映射文件就用多个mapping标签配置
要想进行Hibernate的测试,需要以下几步
public class MyTest {
@Test
public void test1() throws HibernateException {
Customer customer = new Customer();
customer.setAge(21);
customer.setName("丽丽");
customer.setGender("女");
customer.setLevel("VIP一姐");
//1、读取hibernate.cfg.xml文件
Configuration cfg = new Configuration();
cfg.configure();
//2、创建SessionFactory工厂
SessionFactory factory = cfg.buildSessionFactory();
//3、创建Session对象
Session session = factory.openSession();
//4、开启事务
Transaction tx = session.beginTransaction();
//5、执行添加操作
session.save(customer);
//6、提交事务
tx.commit();
//7、关闭资源
session.close();
}
}
【hibernate核心接口有】:
Configuration 接口负责管理Hibernate 的配置信息。它包括如下内容:
Hibernate运行的底层信息:数据库的URL、用户名、密码、JDBC驱动类,数据库Dialect,数据库连接池等。
Hibernate映射文件(*.hbm.xml)。
作用就是加载Hibernate的核心配置文件。
注意事项:
Configuration对象是一个单例的
Configuration config=new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
用来产生和管理 Session :应用程序从SessionFactory(会话工厂)里获得 Session(会话)实例。通常情况下每个应用只需要一个SessionFactory(单例)openSession 每次都是新的,需要close注意事项:
SessionFactory也是单例的,一个项目只需要创建一个sessionFactory对象
Session接口用于操作对象,有一些CRUD的方法
Session是Hibernate持久化操作的基础,与Web层的HttpSession没什么关系。创建Session的方式有二:
Session session = sessionFactory.getCurrentSession();//获取当前线程中的session对象
Session session = sessionFactory.openSession();//创建一个新的session对象

从这里就可看出Session是一个非线程安全的对象
CURD(增删查改)
Transaction接口的作用是用于执行事务的操作
Transaction的方法:
用于执行Hibernate’的HQL查询

【HibernateUtil工具类的抽取】
public class HibernateUtil {
private static Configuration cfg = null;
private static SessionFactory factory =null;
// 使用动态代码块来实现之家再一次的效果
static {
cfg = new Configuration();
cfg.configure();
factory = cfg.buildSessionFactory();
}
/**
* 获取Session
* @return
*/
public static Session getConnection(){
//3、创建Session对象
Session session = factory.openSession();
return session;
}
/**
* 释放资源
* @param session
*/
public static void closeSession(Session session){
session.close();
}
}
回顾上面介绍的Session的常用方法:save保存,update更新,get查找,delete删除
/**
* 增加save方法
* @throws HibernateException
*/
@Test
public void test1() throws HibernateException {
Customer customer = new Customer();
customer.setAge(78);
customer.setName("李老头");
customer.setGender("男");
customer.setLevel("农民");
Session session = HibernateUtil.getConnection();
//4、开启事务
Transaction tx = session.beginTransaction();
//5、执行添加操作
session.save(customer);
//6、提交事务
tx.commit();
//7、关闭资源
HibernateUtil.closeSession(session);
}
/**
* 更新update方法
* @throws HibernateException
*/
@Test
public void test2() throws HibernateException {
Customer customer = new Customer();
customer.setId(3);
customer.setAge(78);
customer.setName("李老头");
customer.setGender("1");
customer.setLevel("农民");
Session session = HibernateUtil.getConnection();
//4、开启事务
Transaction tx = session.beginTransaction();
//5、执行添加操作
session.update(customer);
//6、提交事务
tx.commit();
//7、关闭资源
HibernateUtil.closeSession(session);
}
注意:更新必须要传入一个id往实体类里
/**
* 删除delete方法
* @throws HibernateException
*/
@Test
public void test3() throws HibernateException {
Customer customer = new Customer();
customer.setId(3);
customer.setAge(78);
customer.setName("李老头");
customer.setGender("1");
customer.setLevel("农民");
Session session = HibernateUtil.getConnection();
//4、开启事务
Transaction tx = session.beginTransaction();
//5、执行添加操作
session.delete(customer);
//6、提交事务
tx.commit();
//7、关闭资源
HibernateUtil.closeSession(session);
}
注意:删除也是要传入Id
get和load方法都可以实现查询的操作,但是区别在于load有一个延迟加载的概念
/**
* 查询get/load方法
* @throws HibernateException
*/
@Test
public void test4() throws HibernateException {
Session session = HibernateUtil.getConnection();
//4、开启事务
Transaction tx = session.beginTransaction();
//5、执行添加操作
// Customer customer1 = session.get(Customer.class, 2);
Customer customer1 = session.load(Customer.class, 2);
System.out.println(customer1);
//6、提交事务
tx.commit();
//7、关闭资源
HibernateUtil.closeSession(session);
}