什么是hibernate?
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。
什么是ORM?
Object Relational Mapping,对象关系映射,为了解决传统jdbc中对object的参数改变而引起的一系列修改的办法。强调将java对象和关系型数据库(如:MySQL) 建立一种关系,直接操作java对象就相当于操作表。
映射关系通过配置(XML)实现。
Hibernate环境搭建
版本:Hibernate3.x Hibernate4.x(过渡版) Hibernate5.x(最新版) 。
本学习笔记使用的是 hibernate-release-5.0.7.Final版本。
下载Hibernate的压缩包
去官网~ 下载完成后解压 里面有一个required文件夹,这个文件夹里面的jar包是使用hibernate必须的jar包
创建一个项目,引入jar包
引入jar包清单:
数据库驱动包
Hibernate开发必备的jar包
日志记录包
完整清单如下:
创建表和实体类
CREATE DATABASE hibernate_day01;
SELECT Hibernate_day01;
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;
package com.aloha.hibernate.demo1;
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 Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
public String getCust_mobile() {
return cust_mobile;
}
public void setCust_mobile(String cust_mobile) {
this.cust_mobile = cust_mobile;
}
}
表中的列名最好和实体类的成员变量名称一致。
创建映射关系
映射关系通过配置文件xml来配置,这样可以有利于我们后期对表结构修改的时候尽量少的动java代码。
配置文件放在对应包目录下,可以随意命名,但是最好还是统一命名规范为: 类名.hbm.xml 。 下面是我写的Customer.hbm.xml用来建立java类和表的关系,表主键与java类中对应成员变量的关系以及表中列与java类的对应成员变量的关系。
<?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="com.aloha.hibernate.demo1.Customer" table="cst_customer">
<id name="cust_id" column="cust_id" >
<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>
dtd约束怎么引入:hibernate-core-5.0.7.Final.jar/org.hibernate/hibernate-mapping-3.0.dtd
在这个文件里包含了引入映射dtd约束的语句,语句在上例中写出了。这时就可以些hibernate-mapping的标签了。
类表映射 中:主键映射、成员映射。
创建一个hibernate核心配置文件
核心配置文件位置是在src文件下,名称固定为:hibernate.cfg.xml。主要配置jdbc,内容如下:
<?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.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_day01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 配置hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 可选配置:打印sql语句到控制台上,格式化sql语句 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping resource="com/aloha/hibernate/demo1/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
dtd约束怎么引入:hibernate-core-5.0.7.Final.jar/org.hibernate/hibernate-configuration-3.0.dtd
在这个文件里包含了引入核心配置dtd约束的语句,语句在上例中写出了。这时就可以写hibernate-configuration的标签了。
Hibernate入门
搭建完成Hibernate环境,写好配置文件后,我们就可以开始写执行的java文件的,一个原生的写入案例:
@Test
public void test1(){
//1.加载核心配置文件
Configuration configuration = new Configuration().configure();
//2.创建SessionFactory对象:类似JDBC连接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
//3.通过SessionFactory获取Session对象:类似Connection
Session session = sessionFactory.openSession();
//4.手动开启事务:hibernate5以后以可不用了,但是为了兼容性,还是写着把
Transaction transaction = session.beginTransaction();
//5.编写代码
Customer customer = new Customer();
customer.setCust_name("aloha");
session.save(customer);
//6.事务提交
transaction.commit();
//7.资源释放
session.close();
}
我们往数据库中插入了一条cust_name为aloha的记录,结果如下:
hibernate配置
-
-
- Hibernate的映射的配置
- 映射的配置
- Hibernate的映射的配置
-
- 【class标签的配置】
- 标签用来建立类与表的映射关系
- 属性:
- name :类的全路径
- table :表名(类名与表名一致,table可以省略)
- catalog :数据库名
- 【id标签的配置】
- 标签用来建立类中的属性与表中的主键的对应关系
- 属性:
- name :类中的属性名
- column :表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
- length :长度
- type :类型
- 【property标签的配置】
- 标签用来建立类中的普通属性与表的字段的对应关系
- 属性:
- name :类中的属性名
- column :表中的字段名
- length :长度
- type :类型
- not-null :设置非空
- unique :设置唯一
-
-
- Hibernate的核心的配置
- Hibernate的核心配置方式(了解)
- Hibernate的核心的配置
-
- 一种方式:属性文件的方式
- hibernate.properties
- hibernate.connection.driver_class=com.mysql.jdbc.Driver
- …
- hibernate.show_sql=true
- 属性文件的方式不能引入映射文件(手动编写代码加载映射文件)
- hibernate.properties
- 二种方式:XML文件的方式
- hibernate.cfg.xml
-
- 核心的配置
-
- hibernate.cfg.xml
- 必须的配置
- 连接数据库的基本的参数
- 驱动类
- url路径
- 用户名
- 密码
- 方言
- 连接数据库的基本的参数
- 可选的配置
- 显示SQL :hibernate.show_sql
- 格式化SQL :hibernate.format_sql
- 自动建表 :hibernate.hbm2ddl.auto
- none :不使用hibernate的自动建表
- create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
- create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
- update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
- validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
- 映射文件的引入
- 引入映射文件的位置
核心配置
1.
- 必须的配置
- 连接数据库的基本的参数
- 驱动类
- url路径
- 用户名
- 密码
- 方言
- 连接数据库的基本的参数
- 可选的配置
- 显示SQL :hibernate.show_sql
- 格式化SQL :hibernate.format_sql
- 自动建表 :hibernate.hbm2ddl.auto
- none :不使用hibernate的自动建表
- create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
- create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
- update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
- validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
- 映射文件的引入
- 引入映射文件的位置
Hibernate核心API
Configuration:Hibernate的配置对象
这个类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate的启动过程中,Configuration类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。虽然Configuration类在整个Hibernate项目中只扮演着一个很小的角色,但它是启动Hibernate时所遇到的第一个对象。
作用:
加载核心配置文件
hibernate.properties
Configuration cfg = new Configuration();
hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
手动加载映射:
configuration.addResource("映射文件路径");
SessionFactory: Session工厂
SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。
内部维护了Hibernate的连接池和Hibernate的二级缓存。(企业里二级缓存用的时redis)。是线程安全的对象。
需要引入C3P0连接池时,我们可以在下载hibernate的hibernate-release-5.0.7.Final\lib\optional\c3p0路径中的3个jar包导入项目中,将C3P0的配置代码写入hibernate.cfg.xml中:
<!-- 配置C3P0连接池 -->
<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>
这是一个重量级的对象,为了防止重复创建浪费资源,我们创建一个工具类:
package com.aloha.hibernate.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* hibernate的工具类
* @author malaganguo
*
*/
public class HibernateUtils {
public static final Configuration cfg;
public static final SessionFactory sf;
static{
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
/**
* 获取session对象
* @return 返回session对象
*/
public static Session openSession(){
return sf.openSession();//这个openSession()方法来自SessionFactory
}
}
Session:连接对象
类似Connection对象,Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句)。但需要注意的是Session对象是非线程安全的。同时,Hibernate的session不同于JSP应用中的HttpSession。这里当使用session这个术语时,其实指的是Hibernate中的session,而以后会将HttpSession对象称为用户session。
Hibernate中的Session是Hibernate与数据库链接的对象。是线程不安全的。是与数据库交互的桥梁。
Session 中的API
保存方法: Serializable save(Object obj) ;
查询方法:(hibernate版本大于3.x才有的泛型) T find(Class c, Serializable id); T load(Class c, Serializable id);
查询方法演示以及find,load方法的区别:
/**
* 查询客户
*/
@Test
public void test2(){
Session session =HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//get方法查询
Customer customer = session.get(Customer.class, 1l);
System.out.println(customer);
//load方法查询
Customer customer1 = session.load(Customer.class, 1l);
System.out.println(customer1);
/**
* 两种查询方式的打印语句与查询结果完全相同,区别是?
* get方法采用立即加载,执行到这行代码时就会马上进行查询
* 查询返回的是真实对象
* 查询一个找不到的对象的时候返回null
*
* load方法采用延迟(懒)加载,指执行到这行代码时不会发送SQL语句,真正使用对象时才发送SQL语句,
* 因为id已知,所以用id都不会发语句,也太懒了。
* 查询返回的是代理对象,使用的是javassist.jar包技术产生的代理
* 抛出一个ObjectNotFindException
*/
transaction.commit();
session.close();
}
修改方法:void update(Object obj);
/**
* 修改客户
*/
@Test
public void test3(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
/* //直接创建对象进行修改(不推荐,因为不修改的会被赋null)
Customer customer = new Customer();
customer.setCust_id(4l);
customer.setCust_name("王思聪");
session.update(customer);*/
//先查询再修改(推荐,不会将没有修改的内容赋为null)
Customer customer = session.get(Customer.class, 4l);
customer.setCust_name("王尼玛");
session.update(customer);
transaction.commit();
session.close();
}
直接创建对象进行修改的结果:
我们现在将王思聪的来源依然改为小广告,使用先查询再修改的方式来看看修改的结果:
删除方法: void delete(Object obj);
/**
* 删除客户
*/
@Test
public void test4(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
/*//直接创建对象删除
Customer customer = new Customer();
customer.setCust_id(3l);
session.delete(customer);*/
//先查询再删除
Customer customer = session.get(Customer.class, 2l);
session.delete(customer);
transaction.commit();
session.close();
}
结果:我们删除了两个id为2和3的客户名为aloha的客户记录
保存或更新方法: void saveOrUpdate(Object obj);
/**
* 保存或更新:不设置id——保存;设置id——更新。
*/
@Test
public void test5(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
/*customer.setCust_name("王九蛋");//保存王九蛋*/
customer.setCust_id(6l);
customer.setCust_name("伍佰");//更新id为6的的name为伍佰
session.saveOrUpdate(customer);
transaction.commit();
session.close();
}
查询所有:
/**
* 查询所有:使用HQL或SQL查询
*/
@Test
public void test6(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//接收:HQL对象
//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 query2 = session.createSQLQuery("select * from cst_customer");
List<Object[]> list2 = query2.list();
for (Object[] objects : list2) {
System.out.println(Arrays.toString(objects));
}
transaction.commit();
session.close();
}
HQL查询:
SQL查询:
Transaction:事务对象
常用的就是commit()和rollback()两个方法。提交和回滚。在hibernate5在,如果没有引入C3P0的话,开启事务和提交事务是可以不写的,因为C3P0内代码是可以完成事务的开启和提交的。