Java学习之Hibernate框架使用
Java学习之Hibernate框架使用
0x00 前言
以我看来Hibernate的使用频率其实还是比较可观的,但都说Hibernate比较笨重,这里来学习一波,做个 简单记录。
0x01 使用流程
流程
1、导?相关依赖
2、创建 Hibernate 配置?件
3、创建实体类
4、创建实体类-关系映射?件
5、调? Hibernate API 完成操作
具体操作
mysql
mysql-connector-java
8.0.19
org.hibernate
hibernate-core
5.4.10.Final
org.projectlombok
lombok
1.18.10
- 配置hibernate.cfg.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
root
root
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/test?
useUnicode=true&characterEncoding=UTF-8
10
10000
5000
30
5
10
org.hibernate.dialect.MySQLDialect
true
true
核?配置: session-factory
SessionFactory:针对单个数据库映射经过编译的内存镜像?件,将数据库转换为?个 Java 可以识别的
镜像?件。
构建 SessionFactory ?常耗费资源,所以通常?个?程只需要创建?个 SessionFactory 。
- 创建实体类
import lombok.Data;
import java.util.Set;
@Data
public class Customer {
private Integer id;
private String name;
private Set orders;
}
import lombok.Data;
@Data
public class Orders {
private Integer id;
private String name;
private Customer customer;
}
- 创建实体关系映射?件
import lombok.Data;
@Data
public class People {
private Integer id;
private String name;
private Double money;
}
<?xml version="1.0"?>5、实体关系映射?件注册到 Hibernate 的配置?件中。
6、使? Hibernate API 完成数据操作。
- 实体关系映射?件注册到 Hibernate 的配置?件中。
- 使? Hibernate API 完成数据操作
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
//创建Configuration
Configuration configuration = new
Configuration().configure("hibernate.xml");
//获取SessionFactory
SessionFactory sessionFactory = configuration.buildSessionFactory();
//获取Session
Session session = sessionFactory.openSession();
People people = new People();
people.setName("张三");
people.setMoney(1000.0);
session.save(people);
session.beginTransaction().commit();
session.close();
}
}
配置到映射文件配置到src目录下会读取不到。想要读取到需要在pom.xml下进行配置。
- pom.xml 中需要配置 resource。
src/main/java **/*.xml
0x02 结尾
Hibernate并不是本次主要目的,这里用于做简单记录。