一、Hibernate简介
一个持久层的ORM框架。ORM:Object Relational Mapping(对象关系映射)。指的是将一个Java中的对象与关系型数据库中的表建立一种映射关系,从而操作对象就可以操作数据库中的表。
二、Hibernate入门
1、创建一个项目,引入jar包
hibernate用到的jar包
2、创建表
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;
3、创建实体类
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;
}
}
4、创建映射(*****)
映射需要通过XML的配置文件来完成,这个配置文件可以任意命名。尽量统一命名规范(类名.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="hibernate.demo1.Customer" table="cst_customer">
<!--建立类中属性与表中的主键对应 -->
<id name="cust_id" column="cust_id">
<generator class="native"></generator>
</id>
<!--建立类中的普通属性与表中的字段对应,非主键用property -->
<property name="cust_name" column="cust_name"></property>
<property name="cust_source" column="cust_source"></property>
<property name="cust_industry" column="cust_industry"></property>
<property name="cust_level" column="cust_level"></property>
<property name="cust_phone" column="cust_phone"></property>
<property name="cust_mobile" column="cust_mobile"></property>
</class>
</hibernate-mapping>
5、创建一个Hibernate的核心配置文件(*****)
Hibernate的核心配置文件的名称: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.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">123456</property>
<!--配置Hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--可选配置============= -->
<!--打印Sql -->
<property name="hibernate.show_sql">true</property>
<!--格式化Sql -->
<property name="hibernate.format_sql">true</property>
<!--自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="hibernate/demo1/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6、编写测试代码(*****)
package hibernate.demo1;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
/**
* Hibernate的入门案例
*
* @author Administrator
*
*/
public class HibernateDemo1 {
// 保存客户的案例
@Test
public void demo1() {
// 1、加载Hibernate的核心配置文件
Configuration configuration = new Configuration().configure();
// 2、创建一个SessionFactory对象:类似于JDBC中的连接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 3、通过SessionFactory获取到Session对象:类似于JDBC中的Connection
Session session = sessionFactory.openSession();
// 4、手动开启事务
Transaction transaction = session.beginTransaction();
// 5、编写代码
Customer customer = new Customer();
customer.setCust_name("张三");
customer.setCust_source("小广告");
customer.setCust_industry("IT");
customer.setCust_level("架构师");
customer.setCust_phone("18756696325");
customer.setCust_mobile("858585855");
session.save(customer);
// 6、事务提交
transaction.commit();
// 7、资源释放
session.close();
}
}
三、Hibernate5常见配置
1、配置XML提示问题
2、Hibernate的映射的配置
【class标签的配置】
标签用来建立类与表的映射关系
属性:
name :类的全路径
table :表名(类名与表名一致,table可以省略)
catalog :数据库名
【id标签的配置】
标签用来建立类中的属性与表中的主键的对应关系
属性:
name :类中的属性名
column :表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
length :长度
type :类型
【property标签的配置】
标签用来建立类中的普通属性与表的字段的对应关系
属性:
name :类中的属性名
column :表中的字段名
length :长度(自动建表的时候设置的长度,不然就是默认值)
type :类型 (可不写,hibernate自动转换,或者写java中的类型,如java.lang.String),又或者写string
not-null :设置非空
unique :设置唯一
3、Hibernate的核心的配置
Hibernate的核心配置方式(了解)
一种方式:属性文件的方式
hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver
…
hibernate.show_sql=true
属性文件的方式不能引入映射文件(手动编写代码加载映射文件)
二种方式:XML文件的方式
hibernate.cfg.xml
核心的配置
必须的配置
1、连接数据库的基本的参数
驱动类
url路径
用户名
密码
2、方言
可选的配置
1、显示SQL :hibernate.show_sql
2、格式化SQL :hibernate.format_sql
3、自动建表 :hibernate.hbm2ddl.auto
none :不使用hibernate的自动建表
create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
<property name="hibernate.hbm2ddl.auto">update</property>
映射文件的引入
引入映射文件的位置
<mapping resource="hibernate/demo1/Customer.hbm.xml" />
四、Hibernate的核心API
1、Configuration:Hibernate的配置对象
Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。虽然Configuration 类在整个Hibernate 项目中只扮演着一个很小的角色,但它是启动hibernate 时所遇到的第一个对象。
作用:
加载核心配置文件
a 属性文件
hibernate.properties
Configuration cfg=new Configuration();
b xml文件
hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
加载映射文件
手动加载映射
configuration.addResource("hibernate/demo1/Customer.hbm.xml");
2、SessionFactory:Session工厂
SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存(不用了,关于缓存目前大多使用额是Redis)。是线程安全的对象。一个项目创建一个对象即可。
配置连接池:(了解)
<!-- 配置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 hibernate.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate的工具类
*
* @author Administrator
*
*/
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();
}
}
工具类测试
package hibernate.demo1;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import hibernate.utils.HibernateUtils;
/**
* Hibernate的工具类的测试
*
* @author Administrator
*
*/
public class HibernateDemo2 {
// 保存客户
@Test
public void demo1() {
// 1、通过HibernateUtils工具类获取到Session对象
Session session = HibernateUtils.openSession();
// 2、手动开启事务
Transaction transaction = session.beginTransaction();
// 3、编写代码
Customer customer = new Customer();
customer.setCust_name("李四");
customer.setCust_source("招聘群");
customer.setCust_industry("IT");
customer.setCust_level("实习生");
customer.setCust_phone("18787878787");
customer.setCust_mobile("15959595959");
session.save(customer);
// 4、事务提交
transaction.commit();
// 5、资源释放
session.close();
}
}
3、Session:类似Connection对象是连接对象
Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句)。但需要注意的是Session对象是非线程安全的。同时,Hibernate的session不同于JSP应用中的HttpSession。这里当使用session这个术语时,其实指的是Hibernate中的session,而以后会将HttpSession对象称为用户session。
Session代表的是Hibernate与数据库的链接对象。不是线程安全的。与数据库交互桥梁。
Session中的API
保存方法:
Serializable save(Object obj);
会返回保存等操作的id值。
查询方法:
T get(Class c,Serializable id);
T load(Class c,Serializable id);
**get方法和load方法的区别?(面试常问)
/**
* get方法和load方法的区别:
*
* get方法:
* 1、采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询;
* 2、查询后返回的是真实对象本身;
* 3、查询一个找不到的对象的时候,返回null。
* load方法:
* 1、采用的是延迟加载(lazy加载),执行到这行代码的时候,不回发送SQL语句,当真正使用这对象除了id以外其他属性的时候才会发送SQL语句;
* 2、返回的是代理对象;javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
* 3、查询一个找不到的对象的时候,返回ObjectNotFoundException。
*/
/**
* 查询操作
*/
@Test
public void demo2() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
// 使用get方法来进行查询
Customer customer = session.get(Customer.class, 1l);// 发送SQL语句
System.out.println(customer);
transaction.commit();
session.close();
}
/**
* 查询操作
*/
@Test
public void demo3() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
// 使用get方法来进行查询
Customer customer = session.load(Customer.class, 1l);
System.out.println(customer.getCust_id());//不会发送SQL语句
System.out.println(customer);//会发送SQL语句
transaction.commit();
session.close();
}
修改方法
void update(Object obj);
/**
* 修改操作
*/
@Test
public void demo4(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//直接创建对象,进行修改,不推荐使用,对于没修改的属性会直接置为null
/* Customer customer = new Customer();
customer.setCust_id(1l);
customer.setCust_name("王五");
session.update(customer);*/
//先查询,再修改(推荐)
Customer customer=session.get(Customer.class, 2l);
customer.setCust_name("王五");
session.update(customer);
transaction.commit();
session.close();
}
删除方法
void delete(Object obj);
/**
* 删除操作
*/
@Test
public void demo5(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
//直接创建对象,再删除
/* Customer customer = new Customer();
customer.setCust_id(2l);
session.delete(customer);*/
//先查询再删除(推荐使用)--级联删除
Customer customer=session.get(Customer.class, 2l);
session.delete(customer);
transaction.commit();
session.close();
}
保存或更新方法(不常用)
void saveOrUpdate(Object obj)
/**
* 保存或更新操作(有id的时候执行更新操作,没有id的时候执行保存操作)
*/
@Test
public void demo6(){
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
/* Customer customer = new Customer();
customer.setCust_name("赵四");
session.saveOrUpdate(customer);*/
Customer customer = new Customer();
customer.setCust_id(3l);
customer.setCust_name("赵六");
session.saveOrUpdate(customer);
transaction.commit();
session.close();
}
查询所有方法
/**
* 查询所有
*/
@Test
public void demo7(){
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 query=session.createSQLQuery("select * from cst_customer");
List<Object[]> list=query.list();
for(Object[] objects:list){
System.out.println(Arrays.toString(objects));
}
transaction.commit();
session.close();
}
4、Transaction:事务对象
Transaction 接口是一个可选的API,可以选择不使用这个接口,取而代之的是Hibernate 的设计者自己写的底层事务处理代码。 Transaction 接口是对实际事务实现的一个抽象,这些实现包括JDBC的事务、JTA 中的UserTransaction、甚至可以是CORBA 事务。之所以这样设计是能让开发者能够使用一个统一事务的操作界面,使得自己的项目可以在不同的环境和容器之间方便地移植。
Hibernate中管理事务的对象。
commit();
rollback();
总结
hibernate5的连接池没有配置C3P0连接池可以不写事务提交Transaction transaction = session.beginTransaction();
默认为自动提交的,但是hibernate3中是必须要提交事务的,所以在hibernate5中;
无论有没有配置C3P0连接池,最好都写一下开启事务和提交事务的代码。