Hibernate查询、连接池、二级缓存
Hibernate第三天:
1. 对象状态
2. session缓存
3. lazy懒加载
4. 映射
一对一对映射
组件/继承映射
目标:
一、hibernate查询
二、hibernate对连接池的支持
三、二级缓存
四、Hibernate与Struts小案例(项目中session的管理方式)
一、hibernate查询
1. 查询概述
1) Get/load主键查询
2) 对象导航查询
3) HQL查询, Hibernate Query language hibernate 提供的面向对象的查询语言。
4) Criteria 查询, 完全面向对象的查询(Query By Criteria ,QBC)
5) SQLQuery, 本地SQL查询
缺点:不能跨数据库平台: 如果该了数据库,sql语句有肯能要改
使用场景: 对于复杂sql,hql实现不了的情况,可以使用本地sql查询。
HQL查询
public class Dept {
private int deptId;
private String deptName;
// 【一对多】 部门对应的多个员工
private Set<Employee> emps = new HashSet<Employee>();
<hibernate-mapping package="cn.itcast.a_query">
<class name="Dept" table="t_dept" >
<id name="deptId">
<generator class="native"></generator>
</id>
<property name="deptName" length="20"></property>
<set name="emps">
<key column="dept_id"></key>
<one-to-many class="Employee"/>
</set>
</class>
<!-- 存放sql语句 -->
<query name="getAllDept">
<![CDATA[
from Dept d where deptId < ?
]]>
</query>
</hibernate-mapping>
public class Employee {
private int empId;
private String empName;
private double salary;
// 【多对一】员工与部门
private Dept dept;;
<hibernate-mapping package="cn.itcast.a_query">
<class name="Employee" table="t_employee">
<id name="empId">
<generator class="native"></generator>
</id>
<property name="empName" length="20"></property>
<property name="salary" type="double"></property>
<many-to-one name="dept" column="dept_id" class="Dept"></many-to-one>
</class>
</hibernate-mapping>
public class App_hql {
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(Dept.class)
.addClass(Employee.class) // 测试时候使用
.buildSessionFactory();
}
/*
* 1) Get/load主键查询
2) 对象导航查询
3) HQL查询, Hibernate Query language hibernate 提供的面向对象的查询语言。
4) Criteria 查询, 完全面向对象的查询(Query By Criteria ,QBC)
5) SQLQuery, 本地SQL查询
*/
@Test
public void all() {
Session session = sf.openSession();
session.beginTransaction();
//1) 主键查询
// Dept dept = (Dept) session.get(Dept.class, 12);
// Dept dept = (Dept) session.load(Dept.class, 12); //懒加载
//2) 对象导航查询
// Dept dept = (Dept) session.get(Dept.class, 12);
// System.out.println(dept.getDeptName());
// System.out.println(dept.getEmps());
// 3) HQL查询
// 注意:使用hql查询的时候 映射文件中auto-import="true" 要设置true,
// 如果是false,写hql的时候,要指定类的全名
// Query q = session.createQuery("from Dept");
// System.out.println(q.list());
// a. 查询全部列
// Query q = session.createQuery("from Dept"); //OK
// Query q = session.createQuery("select * from Dept"); //NOK, 错误,不支持 *
// Query q = session.createQuery("select d from Dept d"); // OK
// System.out.println(q.list());
// b. 查询指定的列 【返回对象数据Object[] 】
// Query q = session.createQuery("select d.deptId,d.deptName from Dept d");
// System.out.println(q.list());
// c. 查询指定的列, 自动封装为对象 【必须要提供带参数构造器】
// Query q = session.createQuery("select new Dept(d.deptId,d.deptName) from Dept d");
// System.out.println(q.list());
// d. 条件查询: 一个条件/多个条件and or/between and/模糊查询
// 条件查询: 占位符
// Query q = session.createQuery("from Dept d where deptName=?");
// q.setString(0, "财务部");
// q.setParameter(0, "财务部");
// System.out.println(q.list());
// 条件查询: 命名参数
// Query q = session.createQuery("from Dept d where deptId=:myId or deptName=:name");
// q.setParameter("myId", 12);
// q.setParameter("name", "财务部");
// System.out.println(q.list());
// 范围
// Query q = session.createQuery("from Dept d where deptId between ? and ?");
// q.setParameter(0, 1);
// q.setParameter(1, 20);
// System.out.println(q.list());
// 模糊
// Query q = session.createQuery("from Dept d where deptName like ?");
// q.setString(0, "%部%");
// System.out.println(q.list());
// e. 聚合函数统计
// Query q = session.createQuery("select count(*) from Dept");
// Long num = (Long) q.uniqueResult();
// System.out.println(num);
// f. 分组查询
//-- 统计t_employee表中,每个部门的人数
//数据库写法:SELECT dept_id,COUNT(*) FROM t_employee GROUP BY dept_id;
// HQL写法
// Query q = session.createQuery("select e.dept, count(*) from Employee e group by e.dept");
// System.out.println(q.list());
session.getTransaction().commit();
session.close();
}
// g. 连接查询
@Test
public void join() {
Session session = sf.openSession();
session.beginTransaction();
//1) 内连接 【映射已经配置好了关系,关联的时候,直接写对象的属性即可】
// Query q = session.createQuery("from Dept d inner join d.emps");
//2) 左外连接
// Query q = session.createQuery("from Dept d left join d.emps");
//3) 右外连接
Query q = session.createQuery("from Employee e right join e.dept");
q.list();
session.getTransaction().commit();
session.close();
}
// g. 连接查询 - 迫切连接
@Test
public void fetch() {
Session session = sf.openSession();
session.beginTransaction();
//1) 迫切内连接 【使用fetch, 会把右表的数据,填充到左表对象中!】
// Query q = session.createQuery("from Dept d inner join fetch d.emps");
// q.list();
//2) 迫切左外连接
Query q = session.createQuery("from Dept d left join fetch d.emps");
q.list();
session.getTransaction().commit();
session.close();
}
// HQL查询优化
@Test
public void hql_other() {
Session session = sf.openSession();
session.beginTransaction();
// HQL写死
// Query q = session.createQuery("from Dept d where deptId < 10 ");
// HQL 放到映射文件中
Query q = session.getNamedQuery("getAllDept");
q.setParameter(, );
System.out.println(q.list());
session.getTransaction().commit();
session.close();
}
}
Criteria 查询
public class App_criteria {
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(Dept.class)
.addClass(Employee.class) // 测试时候使用
.buildSessionFactory();
}
/*
* 1) Get/load主键查询
2) 对象导航查询
3) HQL查询, Hibernate Query language hibernate 提供的面向对象的查询语言。
4) Criteria 查询, 完全面向对象的查询(Query By Criteria ,QBC)
5) SQLQuery, 本地SQL查询
*/
//4) Criteria 查询,
@Test
public void criteria() {
Session session = sf.openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Employee.class);
// 构建条件
criteria.add(Restrictions.eq());
// criteria.add(Restrictions.idEq(12)); // 主键查询
System.out.println(criteria.list());
session.getTransaction().commit();
session.close();
}
// 5) SQLQuery, 本地SQL查询
// 不能跨数据库平台: 如果该了数据库,sql语句有肯能要改。
@Test
public void sql() {
Session session = sf.openSession();
session.beginTransaction();
SQLQuery q = session.createSQLQuery("SELECT * FROM t_Dept limit 5;")
.addEntity(Dept.class); // 也可以自动封装
System.out.println(q.list());
session.getTransaction().commit();
session.close();
}
}
SQLQuery, 本地SQL查询
// 5) SQLQuery, 本地SQL查询
// 不能跨数据库平台: 如果该了数据库,sql语句有肯能要改。
@Test
public void sql() {
Session session = sf.openSession();
session.beginTransaction();
SQLQuery q = session.createSQLQuery("SELECT * FROM t_Dept limit 5;")
.addEntity(Dept.class); // 也可以自动封装
System.out.println(q.list());
session.getTransaction().commit();
session.close();
}
2. 分页查询
分页SQL:先查询总记录数,再分页查询。
public class App_page {
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(Dept.class)
.addClass(Employee.class) // 测试时候使用
.buildSessionFactory();
}
// 分页查询
@Test
public void all() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Employee");
// 从记录数
ScrollableResults scroll = q.scroll(); // 得到滚动的结果集
scroll.last(); // 滚动到最后一行
;// 得到滚到的记录数,即总记录数
// 设置分页参数
q.setFirstResult();
q.setMaxResults();
// 查询
System.out.println(q.list());
System.out.println("总记录数:" + totalCount);
session.getTransaction().commit();
session.close();
}
}
二、hibernate对连接池的支持
连接池,
作用: 管理连接;提升连接的利用效率!
常用的连接池: C3P0连接池
Hibernate 自带的也有一个连接池,且对C3P0连接池也有支持!
Hbm 自带连接池:只维护一个连接,比较简陋。
可以查看hibernate.properties文件查看连接池详细配置:
#################################
### Hibernate Connection Pool ###
#################################
hibernate.connection.pool_size 1 【Hbm 自带连接池: 只有一个连接】
###########################
### C3P0 Connection Pool### 【Hbm对C3P0连接池支持】
###########################
#hibernate.c3p0.max_size 2 最大连接数
#hibernate.c3p0.min_size 2 最小连接数
#hibernate.c3p0.timeout 5000 超时时间
#hibernate.c3p0.max_statements 100 最大执行的命令的个数
#hibernate.c3p0.idle_test_period 3000 空闲测试时间
#hibernate.c3p0.acquire_increment 2 连接不够用的时候, 每次增加的连接数
#hibernate.c3p0.validate false
【Hbm对C3P0连接池支持, 核心类】
告诉hib使用的是哪一个连接池技术。
#hibernate.connection.provider_class org.hibernate.connection.C3P0ConnectionProvider
Hibernate.cfg.xml 中增加连接池相关配置:
<!-- 【连接池配置】 -->
<!-- 配置连接驱动管理类 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 配置连接池参数信息 -->
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.max_size">4</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.idle_test_period">30000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
三、二级缓存
Hibernate提供的缓存
有一级缓存、二级缓存。 目的是为了减少对数据库的访问次数,提升程序执行效率!
一级缓存:基于Session的缓存,缓存内容只在当前session有效,session关闭,缓存内容失效!
特点:
作用范围较小! 缓存的时间短。
缓存效果不明显。在短时间内多次操作数据库时,效果明显
概述
二级缓存:
Hibernate提供了基于应用程序级别的缓存, 可以跨多个session,即不同的session都可以访问缓存数据。 这个换存也叫二级缓存。
Hibernate提供的二级缓存有默认的实现,且是一种可插配的缓存框架!如果用户想用二级缓存,只需要在hibernate.cfg.xml中配置即可; 不想用,直接移除,不影响代码。
如果用户觉得hibernate提供的缓存框架不好用,自己可以换其他的缓存框架或自己实现缓存框架都可以。
使用二级缓存
查看hibernate.properties配置文件,二级缓存如何配置?
##########################
### Second-level Cache ###
##########################
#hibernate.cache.use_second_level_cache false【二级缓存默认不开启,需要手动开启】
#hibernate.cache.use_query_cache true 【开启查询缓存】
## choose a cache implementation 【二级缓存框架的实现】
#hibernate.cache.provider_class org.hibernate.cache.EhCacheProvider
#hibernate.cache.provider_class org.hibernate.cache.EmptyCacheProvider
hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider 默认实现
#hibernate.cache.provider_class org.hibernate.cache.TreeCacheProvider
#hibernate.cache.provider_class org.hibernate.cache.OSCacheProvider
#hibernate.cache.provider_class org.hibernate.cache.SwarmCacheProvider
二级缓存,使用步骤
1) 开启二级缓存
2)指定缓存框架
3)指定那些类加入二级缓存
4)测试
测试二级缓存!
缓存策略
<class-cache usage="read-only"/> 放入二级缓存的对象,只读;
<class-cache usage="nonstrict-read-write"/> 非严格的读写
<class-cache usage="read-write"/> 读写; 放入二级缓存的对象可以读、写;
<class-cache usage="transactional"/> (基于事务的策略)
集合缓存
<!-- 集合缓存[集合缓存的元素对象,也加加入二级缓存] -->
<collection-cache usage="read-write" collection="cn.itcast.b_second_cache.Dept.emps"/>
查询缓存
list() 默认情况只会放入缓存,不会从一级缓存中取!
使用查询缓存,可以让list()查询从二级缓存中取!
hibernate.cfg.xml
<hibernate-configuration>
<!-- 通常,一个session-factory节点代表一个数据库 -->
<session-factory>
<!-- 1. 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hib_demo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!--
数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 2. 其他相关配置 -->
<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 2.2 格式化sql
<property name="hibernate.format_sql">true</property> -->
<!-- 2.3 自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置session的创建方式:线程方式创建session对象 -->
<property name="hibernate.current_session_context_class">thread</property>
<!--****************** 【连接池配置】****************** -->
<!-- 配置连接驱动管理类 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 配置连接池参数信息 -->
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.max_size">4</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.idle_test_period">30000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<!--****************** 【二级缓存配置】****************** -->
<!-- a. 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- b. 指定使用哪一个缓存框架(默认提供的) -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- c. 指定哪一些类,需要加入二级缓存 -->
<class-cache usage="read-write" class="cn.itcast.b_second_cache.Dept"/>
<class-cache usage="read-only" class="cn.itcast.b_second_cache.Employee"/>
<!-- 集合缓存[集合缓存的元素对象,也加加入二级缓存] -->
<collection-cache usage="read-write" collection="cn.itcast.b_second_cache.Dept.emps"/>
<!-- 3. 加载所有映射
<mapping resource="cn/itcast/a_hello/Employee.hbm.xml"/>
-->
</session-factory>
</hibernate-configuration>
public class App {
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(Dept.class)
.addClass(Employee.class) // 测试时候使用
.buildSessionFactory();
}
// 1. 测试二级缓存的使用
// 没有/有用 二级缓存
@Test
public void testCache() {
Session session1 = sf.openSession();
session1.beginTransaction();
// a. 查询一次
Dept dept = (Dept) session1.);
dept.getEmps().size();// 集合
session1.getTransaction().commit();
session1.close();
System.out.println("------");
// 第二个session
Session session2 = sf.openSession();
session2.beginTransaction();
// a. 查询一次
dept = (Dept) session2.); // 二级缓存配置好; 这里不查询数据库
dept.getEmps().size();
session2.getTransaction().commit();
session2.close();
}
@Test
public void listCache() {
Session session1 = sf.openSession();
session1.beginTransaction();
// HQL查询 【setCacheable 指定从二级缓存找,或者是放入二级缓存】
Query q = session1.createQuery("from Dept").setCacheable(true);
System.out.println(q.list());
session1.getTransaction().commit();
session1.close();
Session session2 = sf.openSession();
session2.beginTransaction();
q = session2.createQuery("from Dept").setCacheable(true);
System.out.println(q.list()); // 不查询数据库: 需要开启查询缓存
session2.getTransaction().commit();
session2.close();
}
}
四、项目中session的管理方式
Session的创建方式:
@Test
public void testSession() throws Exception {
//openSession: 创建Session, 每次都会创建一个新的session
Session session1 = sf.openSession();
Session session2 = sf.openSession();
System.out.println(session1 == session2);
session1.close();
session2.close();
//getCurrentSession 创建或者获取session
// 线程的方式创建session
// 一定要配置:<property name="hibernate.current_session_context_class">thread</property>
Session session3 = sf.getCurrentSession();// 创建session,绑定到线程
Session session4 = sf.getCurrentSession();// 从当前访问线程获取session
System.out.println(session3 == session4);
// 关闭 【以线程方式创建的session,可以不用关闭; 线程结束session自动关闭】
//session3.close();
//session4.close(); 报错,因为同一个session已经关闭了!
}
四、项目应用
重点:
1. Struts与Hibernate一起使用完成案例开发!
2. Open Session In View 模式应用
需求:
显示部门信息,部门下的所有员工!
【要求:员工信息在jsp页面显示,使用懒加载完成!】
数据库设计:
T_dept/ t_employee
项目框架搭建
a. 引用的jar文件
struts相关jar文件
hibernate相关jar文件
c3p0连接池/数据库驱动包
b. 配置
struts.xml
hibernate.cfg.xml
web.xml 【struts核心过滤器】
c. 公用类
Hibernate查询、连接池、二级缓存的更多相关文章
- hibernate对连接池的支持和HQL查询
hibernate对连接池的支持 连接池, 作用: 管理连接:提升连接的利用效率! 常用的连接池: C3P0连接池 Hibernate 自带的也有一个连接池,且对C3P0连接池也有支持! 只维护一个连 ...
- hibernate框架学习之二级缓存(测试用例)
HqlDemoApp.java package cn.itcast.h3.query.hql; import java.io.Serializable; import org.hibernate.Qu ...
- hibernate框架学习之二级缓存
缓存的意义 l应用程序中使用的数据均保存在永久性存储介质之上,当应用程序需要使用数据时,从永久介质上进行获取.缓存是介于应用程序与永久性存储介质之间的一块数据存储区域.利用缓存,应用程序可以将使用的数 ...
- Java Hibernate 之连接池详解
Hibernate支持第三方的连接池,官方推荐的连接池是C3P0,Proxool,以及DBCP.在配置连接池时需要注意的有三点: 一.Apche的DBCP在Hibernate2中受支持,但在Hiber ...
- java框架篇---hibernate之连接池
Hibernate支持第三方的连接池,官方推荐的连接池是C3P0,Proxool,以及DBCP.在配置连接池时需要注意的有三点: 一.Apche的DBCP在Hibernate2中受支持,但在Hiber ...
- hibernate的一级和二级缓存
一级缓存就是Session级别的缓存,close后就没了. 二级缓存就是SessionFactory级别的缓存,全局缓存,要配置其他插件. 什么样的数据适合存放到第二级缓存中? 1.很少被修改的数据 ...
- Hibernate 集成 Ehcache 开启二级缓存
一.将 Ehcache.xml 放到 classpath 下 <?xml version="1.0" encoding="UTF-8"?> < ...
- hibernate对连接池的支持
连接池, 作用: 管理连接:提升连接的利用效率! 常用的连接池: C3P0连接池 Hibernate 自带的也有一个连接池,且对C3P0连接池也有支持! Hbm 自带连接池: ...
- 【Hibernate】Hibernate系列7之二级缓存
二级缓存 7.1.概述 7.2.配置方法
- Hibernate 性能优化之二级缓存
二级缓存是一个共享缓存,在二级缓存中存放的数据是共享数据特性 修改不能特别频繁 数据可以公开二级缓存在sessionFactory中,因为sessionFactory本身是线程安全,所 ...
随机推荐
- Dubbo服务的搭建与使用
官方地址Dubbo.io Dubbo 主要功能 高并发的负载均衡,多系统的兼容合并(理解不深,不瞎掰了) Dubbo 主要组成有四部分 Zookeeper(服务注册中心) Consumer(服务消费方 ...
- C# 语言规范_版本5.0 (第18章 不安全代码)
1. 不安全代码 **(注:此章对于跨多语言编程开发非常重要,如遇异常无法完成跨语言,建议使用此种方式.) 如前面几章所定义,核心 C# 语言没有将指针列入它所支持的数据类型,从而与 C 和 C++ ...
- Openjudge-NOI题库-出书最多
描述 假定图书馆新进了m(10 ≤ m ≤ 999)本图书,它们都是由n(2 ≤ n ≤ 26)个作者独立或相互合作编著的.假设m本图书编号为整数(1到999),作者的姓名为字母('A'到'Z'),请 ...
- wpf listview 行变色
<ListView x:Name="listView_Date" Grid.Row="3" BorderBrush="{x:Null}" ...
- APP金融安全白皮书十大安全注意事项及各项注意安全
1 信息数据明文发送 2 通信数据可破解 3 敏感数据本地可破解 4 调试信息泄漏 5 敏感信息泄漏 6 密码学误用 7 功能泄漏 8 可二次打包 9 可调式 10 代码可逆向 ----------- ...
- Java中的注释
代码注释是架起程序设计者与程序阅读者之间的通信桥梁,最大限度的提高团队开发合作效率.也是程序代码可维护性的重要环节之一.所以我们不是为写注释而写注释.下面说一下Javadoc注释规范以及楼主在J2EE ...
- Nopi Excel导入
http://download.csdn.net/detail/diaodiaop/7611721 using System.Collections.Generic; using System.Dat ...
- CodeForces 698B Fix a Tree
并查集,构造. 先看一下图的特殊性,按照这种输入方式,一个点的入度最多只有$1$,因此,问题不会特别复杂,画画图就能知道了. 如果给出的序列中已经存在$a[i]=i$,那么随便取一个$a[i]=i$的 ...
- NYIST OJ 题目42 一笔画问题
水题.无向图欧拉通路的判定.用并查集判定是不是连通图! #include<cstdio> #include<cstring> #include<cmath> #in ...
- ios 从前台返回到回台 从后台返回到前台 或者 支付宝支付订单后 对界面进行操作
正常情况下,在AppDelegate中实现下面两个方法,能够监听从后台恢复到前台 - (void)applicationDidEnterBackground:(UIApplication *)appl ...