Hibernate框架的概述
一、框架的概述
1、初次接触框架,那么问题来了,什么是框架?
二、EE的三层架构
1、EE的经典三层结构
三、Hibernate的概述
1、什么是Hhibernate
-
Hibernate :Hibernate是一个持久层的ORM框架。
2、什么是ORM
3、Hibernate的优点
Hibernate的入门
一、Hiernate入门
1、下载Hibernate的开发环境
https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/
2、解压Hibernate
3、创建一个项目,引入jar包:
4、从案例出发,创建数据库和表
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;
5、创建实体类
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;
6、创建映射(重要)
-
映射需要通过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: 完整类名(带完整包结构) table: 数据库表名 --> <class name="com.heer.hibernate.demo1.Customer" table="cst_customer"> <!-- 建立类中的属性与表中的主键对应 --> <!-- id元素:配置主键映射的属性 name:填写主键对应的属性名 column(可选):填写表中的主键列名.默认值:主键会默认使用属性名 type(可选):填写列(属性)的类型。hibernate会自动检测实体的属性类型 每个类型有三种填法:java类型|hibernate类型|数据库类型 not-null(可选):配置该属性(列)是否不能为空。默认值:false length(可选):配置数据库中列的长度。默认值:使用数据库类型的最大长度 --> <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>
7、创建一个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> <!-- 必选属性配置5个 --> <!-- 连接数据库的基本参数 --> <!-- 数据库驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库url --> <property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property> <!-- 数据库连接用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库连接密码 --> <property name="hibernate.connection.password">123456</property> <!-- 配置Hibernate的方言: 不同的数据库中,sql语法稍有区别,指定方言可以让hibernate框架在生成sql语句时,针对数据库的方言生成 sql99标准: DDL:数据定义语言 库表的增删改查 DCL:数据控制语言 事务 权限 DML:数据操纵语言 增删改查 注意:mysql在选择方言时,会选择最短的方言 org.hibernate.dialect.MySQLDialect --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 可选配置3个 --> <!-- 打印SQL语句,将hibernate生成的sql语句打印在控制台 --> <property name="hibernate.show_sql">true</property> <!-- 格式化SQL语句,将hibernate生成的sql语句格式化(缩进) --> <property name="hibernate.format_sql">true</property> <!-- auto schema export 自动导出表结构 ,自动建表 hibernate.hbm2ddl.auto create 自动建表,每次运行框架都会创建新的表,以前的表会被覆盖,数据会丢失(开发环境测试使用) hibernate.hbm2ddl.auto create-drop 自动建表,每次运行框架结束后都会删除多使用的表(开发环境测试使用) hibernate.hbm2ddl.auto update (推荐使用) 自动生成表,如果已经存在则不会生成,直接使用,如果表有变动,自动更新表(不会删除表内容) hibernate.hbm2ddl.auto validate 校验:不自动建表,每次启动会校验数据库中的表是否正确,不正确则校验失败,抛出异常 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置C3P0连接池,别忘了引入jar包 --> <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> <!-- 引入(ORM数据源)映射文件 --> <mapping resource="com/heer/hibernate/demo1/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
8、编写测试代码(重要)
package com.heer.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 hand
*
*/
public class HibernateTestConfig {
@Test
// 保存客户的案例
public void demo1(){
// 1.加载Hibernate的核心配置文件
Configuration configuration = new Configuration().configure();
// 如果是加载的属性文件即hibernate.properties文件,则使用下面的方法,只需要new一个对象即可
// Configuration configuration = new Configuration();
// 若hibernate.cfg.xml文件中没有加入映射文件,可以在此处手动加载
// configuration.addResource("com/heer/hibernate/demo1/Customer.hbm.xml");
// 2.创建一个SessionFactory对象:类似于JDBC中的连接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 3.通过SessionFactory获取到Session对象:类似于JDBC中Connection
Session session = sessionFactory.openSession();
// 4.手动开启事务(在Hibernate5中可以不用管,为了兼容Hibernate3,这块以后交给spring处理)
Transaction transaction = session.beginTransaction();
// 5.编写代码
Customer customer = new Customer();
customer.setCust_name("张三");
// 执行保存
session.save(customer);
// 6.事务提交
transaction.commit();
// 7.资源释放
session.close();
}
}
Hibernate常见的配置
一、XML提示的配置
1、配置XML提示(在没有联网的情况下可以进行自动提示)
二、Hibernate的映射配置
1、映射文件的配置
1) 【class标签的配置】
2) 【id标签的配置】
-
id标签用来建立类中的属性与表中的主键的对应关系
- 属性:
- name :类中的属性名
- column :表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
- length :长度
- type :类型
- 属性:
3) 【property标签的配置】
-
property标签用来建立类中的普通属性与表的字段的对应关系
-
属性:
- name :类中的属性名
- column :表中的字段名
- length :长度
- type :类型
- not-null :设置非空
- unique :设置唯一
-
三、Hibernate的核心文件配置
1、Hibernate的核心配置方式(了解)
1) 第一种方式:属性文件的方式
-
文件名称: hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver … hibernate.show_sql=true
注意:属性文件的方式不能引入映射文件(需要手动编写代码加载映射文件)
2) 第二种方式:XML文件的方式
文件名称: hibernate.cfg.xml
2、核心的配置
-
必选配置
-
可选配置
-
显示SQL :hibernate.show_sql
-
格式化SQL :hibernate.format_sql
-
自动建表 :hibernate.hbm2ddl.auto
-
none :不使用hibernate的自动建表
-
create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
-
create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完之后删除该表。(测试)
-
update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构),推荐使用
-
validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
-
-
映射文件的加载
Hibernate的核心API
一、Hibernate的API
1、Configuration :Hibernate的配置对象
2、SessionFactory :Session工厂
-
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存。是线程安全的对象。一个项目创建一个对象即可。
-
配置C3P0连接池:(了解)
<!-- 配置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.heer.hibernate.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Hibernate的工具类 * 一个项目只会有一个SessionFactory的对象 * @author hand * 2018年11月14日 上午10:03:06 */ public class HibernateUtils { // 定义session创建所需要的Configuration,SessionFactory,都定义成静态的 public static final Configuration cfg; public static final SessionFactory sf; // 对上面的两个对象进行赋值,静态代码块 static{ cfg = new Configuration().configure(); sf = cfg.buildSessionFactory(); } // 对外提供一个方法,返回openSession() public static Session openSession(){ return sf.openSession(); } }
-
3、Session : 类似Connection对象,是连接对象
Session代表的是Hibernate与数据库的链接对象。不是线程安全的。是与数据库交互的桥梁。
1) 保存方法:
-
Serializable save(Object obj);
@Test // 保存基本数据案例 public void testUtil(){ // 获取session对象 Session session = HibernateUtils.openSession(); // 开启事务 Transaction transaction = session.beginTransaction(); Customer customer = new Customer(); customer.setCust_name("王小二"); // session保存,等有了其他的框架之后,上下的所有语句都没有了,只有这一句话 session.save(customer); // 事务提交 transaction.commit(); // 释放资源 session.close(); }
2) 查询方法:
-
T get(Class c,Serializable id);
-
T load(Class c,Serializable id);
-
get方法和load方法的区别?
@Test // 查询操作 // ***get方法和load方法的区别 public void testGetAndLoad(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); /** * get方法 * * 采用的是立即加载,执行到这行代码的时候,就会马上发送sql语句进行查询; * * 查询后返回的是对象本身; * * 查询一个找不到的对象的时候,返回null; * * load方法 * * 采用的是延迟加载(lazy加载),执行到这行代码的时候,不会发送sql语句,当真正使用这个对象的时候才会发送sql语句; * * 查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。 * * 查询一个扎偶倒的对象的时候,返回ObjectNotFoundException异常 * */ // 使用get方法查询 /*Customer customer = session.get(Customer.class, 1l); System.out.println(customer);*/ // 使用load方法查询 Customer customer = session.load(Customer.class, 1l); System.out.println(customer); transaction.commit(); session.close(); }
3) 修改方法
-
void update(Object obj);
@Test // 修改操作 public void testUpdate(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // 直接创建对象,进行修改 /*Customer customer = new Customer(); customer.setCust_id(1l); customer.setCust_name("王二小"); session.update(customer);*/ // 先进行查询,再修改(推荐) Customer customer = session.get(Customer.class, 1l); customer.setCust_name("王小贱"); session.update(customer); transaction.commit(); session.close(); }
4) 删除方法
-
void delete(Object obj);
@Test // 删除操作 public void testDelete(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // 创建对象,进行删除 /*Customer customer = new Customer(); customer.setCust_id(1l); session.delete(customer);*/ // 先进行查询,在进行删除操作(推荐使用)---Hibernate有级联删除,级联删除的条件是先查询后删除 Customer customer = session.get(Customer.class, 2l); session.delete(customer); transaction.commit(); session.close(); }
5) 保存或更新
-
void saveOrUpdate(Object obj);
@Test // 保存或更新操作 public void testSaveOrUpdate(){ 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(4l); // 如果id不存在的话,则会报错 customer.setCust_name("美如画"); session.saveOrUpdate(customer); transaction.commit(); session.close(); }
6) 查询所有
@Test
// 查询所有操作
public void testQuery(){
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:只有在当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();
}