JavaEE之Hibernate(开放源代码的对象关系映射框架)

时间:2023-03-08 16:35:34

Hibernate(开放源代码的对象关系映射框架)

1.简介

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的JaveEE架构中取代CMP,完成数据持久化的重任。

2.ORM

ORM:Object Relational Mapping(对象关系映射)。指将一个Java中的对象与关系型数据库中的表建立一种映射关系,从而通过操作对象就可以操作数据库中的表。JavaEE之Hibernate(开放源代码的对象关系映射框架)

3.Hibernate特点

JavaEE之Hibernate(开放源代码的对象关系映射框架)

4.Hibernate入门

4.1 Hibernate目录结构

JavaEE之Hibernate(开放源代码的对象关系映射框架)

  • documentation Hibernate开发文档

  • lib Hibernate开发包

    • required Hibernate开发必须的依赖包
    • optional Hibernate开发可选jar包
  • project Hibernate提供的项目

4.2Hibernate项目的创建(eclipse)

4.2.1创建数据表(数据库中创建)

CREATE TABLE `cst_customer` (
`cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
`cust_name` VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)',
`cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
`cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '客户所属行业',
`cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
`cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
`cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '移动电话',
PRIMARY KEY (`cust_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

4.2.2创建实体类(与要连接的表相对应)

public class Customer {
private Long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_phone;
private String cust_mobile;
public Customer() {
super();
// TODO Auto-generated constructor stub
}
}

4.2.3创建映射

在与实体类相同的包下创建映射文件Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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="Demo01.Customer" table="cst_customer">
<id name="cust_id" column="cust_id">
<!-- 设置主键的生成策略:native--自增 -->
<generator class="native"/>
</id>
<property name="cust_name" column="cust_name"/>
<property name="cust_source" column="cust_source"/>
<property name="cust_industry" column="cust_industry"/>
<property name="cust_level" column="cust_level"/>
<property name="cust_phone" column="cust_phone"/>
<property name="cust_mobile" column="cust_mobile"/>
</class>
</hibernate-mapping>

4.2.4创建核心配置文件

在src目录下创建hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!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="connection.url" >jdbc:mysql:///hibernate01</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property> <!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property>-->
<!-- 配置数据库方言-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--映射文件路径-->
<mapping resource="Demo01/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>

4.2.5测试代码


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.Test; public class HibernateDemo01 {
@Test
public void demo1(){
//加载hibernate核心配置文件
Configuration configuration = new Configuration().configure();
//创建一个session工厂类似于jdbc的连接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
//通过sessionFactory获取session对象
Session session = sessionFactory.openSession();
//开启事务
Transaction transaction = session.beginTransaction();
//编写代码
Customer customer = new Customer();
customer.setCust_name("gx");
//保存
session.save(customer);
//提交事务
transaction.commit();
//释放资源
session.close();
}
}

5.Hibernate的常见配置

5.1Hibernate映射配置

文件Customer.hbm.xml

  • class标签属性配置

    • 该标签用来建立类与表的映射关系
    • 属性
      • name:类的全路径
      • table :表名(类名和表名如果一致那么table可以省略)
      • ctatlog:数据库名
    <class name="Demo01.Customer" table="cst_customer">
  • id标签配置

    • 标签用来建立类中属性与表中主键的对应关系
    • 属性
      • name:类中的属性
      • column:表中的字段名(类中属性名和表中字段名如果一致那么column可以省略)
      • length:长度
      • type:类型
    <id name="cust_id" column="cust_id">
    <!-- 设置主键的生成策略:native--自增 -->
    <generator class="native"/>
    </id>
  • property

    • 标签用来建立类中普通属性与表字段之间的对应关系
    • 属性
      • name:类中的属性
      • column:表中的字段名
      • length:长度(Hibernate如果在运行前没有建立定义的表,那么在运行时就会自动建表,这时表中对应字段的长度就是此处设置的长度)
      • type:类型
      • not-noll:设置非空
      • unique:是否唯一
     <property name="cust_name" column="cust_name"/>
    <property name="cust_source" column="cust_source"/>
    <property name="cust_industry" column="cust_industry"/>
    <property name="cust_level" column="cust_level"/>
    <property name="cust_phone" column="cust_phone"/>
    <property name="cust_mobile" column="cust_mobile"/>

5.2Hibernate核心配置

两种方式:

1.属性文件配置

hibernate.properties

键值对配置

注意:该方式不能引入配置文件,若想引入需要通过代码配置需要手动编写代码加载映射文件。

2.XMl文件配置

hibernate.cfg.xml

  • 必须的配置

    • 连接数据库的基本参数
      • 驱动类
      • url路径
      • 用户名
      • 密码
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///hibernate01</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">123456</property>
    • 方言
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  • 可选配置

    • 显示sql:hibernate.show_sql
    • 格式化sql:hibernate.format_sql
    • 自动建表:hibernate.hbm2ddl.auto
      • none:不使用Hibernate自动建表
      • create:如果数据库中已经有表,先删除原来的表,在创建新表。如果没有表就新建表
      • create-drop;如果数据库中已经有表,先删除原来的表,在创建新表。如果没有表就新建表。使用完成后删除该表
      • update:如果数据库中有表,就使用原来的表,若没有就新建表。如果映射文件中表字段与数据库中的对应表不一致,那么就会新建对应字段。(即更改表结构)
      • validate:如果没有表,不会创建表,只会使用原有表,作用:校验映射与表结构
    <!-- 打印SQL -->
    <property name="hibernate.show_sql">true</property>
    <!-- 格式化SQL -->
    <property name="hibernate.format_sql">true</property>
    <!-- 自动创建表 -->
    <property name="hibernate.hbm2ddl.auto">create</property>
  • 映射文件的引入

    • 配置映射文件位置(使用mapping标签)
    <mapping resource="hibernate/Demo1/Custmoer.hbm.xml"/>

6.Hibernate的核心API

6.1 Configuration:Hibernate的配置对象

​ Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。虽然Configuration 类在整个Hibernate 项目中只扮演着一个很小的角色,但它是启动hibernate 时所遇到的第一个对象。

6.1.1作用

6.1.1.1加载核心配置文件
  1. hibernate.properties

Configuration configuration = new Configuration();

  1. hibernate.cfg.xml

Configuration configuration = new Configuration().configure();

6.1.1.1.2加载映射文件

配置属性文件时无法加载映射文件故映射文件只能手动加载,xml文件也可以使用该方法加载

configuration.addResource("hibernate/Demo1/Custmoer.hbm.xml");

6.2 SessionFactory:session工厂

SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。

SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存。是对象安全对象,一个项目创建一个对象即可

6.2.1 配置数据库连接池

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--在连接池中可用的数据库连接的最少数目 -->
<property name="c3p0.min_size">5</property>
<!--在连接池中所有数据库连接的最大数目 -->
<property name="c3p0.max_size">20</property>
<!--设定数据库连接的过期时间,以秒为单位,如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
<property name="c3p0.timeout">120</property>
<!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
<property name="c3p0.idle_test_period">3000</property>

6.2.2 抽取工具类

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtils { public static final Configuration cfg;
public static final SessionFactory sf; static {
cfg=new Configuration().configure();
sf=cfg.buildSessionFactory();
} public static Session openSession() {
return sf.openSession();
}
}

6.3 Session:类似Connection对象是连接对象

​ Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句)。但需要注意的是Session对象是非线程安全的。同时,Hibernate的session不同于JSP应用中的HttpSession。这里当使用session这个术语时,其实指的是Hibernate中的session,而以后会将HttpSession对象称为用户session。

Session代表Hibernate与数据库连接池的连接对象。线程不安全,与数据库交互的桥梁

6.3.1 Session中的api

6.3.1.1保存方法

Serialzable save(Object o);

public void demo6() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction(); Customer c = new Customer();
c.setCust_name("gfws");
session.save(c); transaction.commit();
session.close();
}
6.3.1.2 查询方法

T get(Class c,Serializable id);

T load(Class c,Serializable id);

public void demo1() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction(); /**
* get方法
* * 采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
* * 查询后返回是真实对象本身。
* * 查询一个找不到的对象的时候,返回null
*
* load方法
* * 采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
* * 查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
* * 查询一个找不到的对象的时候,返回ObjectNotFoundException
*/
/*Customer customer = session.get(Customer.class, 1l);
System.out.println(customer);*/ Customer customer = session.load(Customer.class, 2l);
System.out.println(customer); transaction.commit();
session.close();
}

查询所有

public void demo5() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction(); //通过HQL:Hibernate Query Language面向对象查询语言
/*Query query = session.createQuery("from Customer");
List<Customer> list = query.list();
for (Customer customer : list) {
System.out.println(customer);
}*/
//使用普通SQL语句查询
SQLQuery sql = session.createSQLQuery("select * from cst_customer");
List<Object[]> list = sql.list();
for (Object[] object : list) {
System.out.println(Arrays.toString(object));
} transaction.commit();
session.close();
}
6.3.1.3 修改方法

void update(Object o);

public void demo2() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//直接创建对象进行修改
/*Customer c = new Customer();
c.setCust_name("hh");
c.setCust_id(1l);*/ //先查询后修改(推荐)
Customer c = session.get(Customer.class, 2l);
c.setCust_name("gx");
session.update(c); transaction.commit();
session.close();
}
6.3.1.4 删除方法

void delete(Object o);

public void demo3() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//直接创建对象进行删除
/*Customer c = new Customer();
c.setCust_id(4l);*/ //先查询后删除(推荐)--级联删除
Customer c = session.get(Customer.class, 1l);
session.delete(c); transaction.commit();
session.close();
}
6.3.1.5 保存或更新

void saveOrUpdate(Object o);

public void demo4() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//如果要删除或保存对象的属性与现有数据库中的都不相同就保存,如有相同就对有相同的那一列修改
Customer c = new Customer();
/*c.setCust_name("wf");*/
c.setCust_id(2l);
c.setCust_name("fx");
session.saveOrUpdate(c);
transaction.commit();
session.close();
}

6.4 Transaction :事务对象

Hibernate中管理事务的对象

commit();

rollback();