hibernate(4)(HQL查询,连接池,二级缓存 ,session管理)
简介:
一、hibernate查询
二、hibernate对连接池的支持
三、二级缓存
四、Hibernate与Struts小案例(项目中session的管理方式)
HQL查询:
如果设置auto-import=talse,查询语句对应的类需要写全名(包括包名),默认是true,不需要写全名的。


默认或者为true可以直接写类名:

HQL语句写法:
1.不能使用*,如果需要可以不写或者使用别名代替:

2.查询指定的列返回数组元素是又是一个object数组对象:

数据效果:

2.查询列可以指定为一个类型的对象,但是必须提供此参数的构造器:

构造方法

3.条件查询:
3.1占位符条件查询

3.2命名参数的条件查询(注意名字前加":"符号),优点是,可以不用在意参数的顺序

4.聚合函数统计的方式:(count(1)只能在数据库中使用,hibernate不支持)

一般还是采用第3种查询主键(坑定没有空值)
聚合函数查询出数量的方法是uniqueResult():

5.分组查询一个问题:在HQL语句中分组字段用的是对象属性(该属性的类型是一个关联类,一般情况使用的都是基本类型的属性字段)

查询字段select e.dept count(*),list()返回是一个Object[] 其中一个属性Dept对象一个属性是long类型
6.连接查询(注意:外连接,数组元素中的数组元素可能为null,迫切外连接的关联的对象为null的情况,需要判断再使用)
回顾sql:内连接只返回匹配的数据,外连接除了返回匹配的数据外,如果是左外连,还有左边未找到匹配的数据以及对应的其他字段值为null,如果是右外连接,则是右

外连接:

6.1.这种连接方式返回的object[]的元素是object数组
例子:

几种连接方式:

这些连接list()得到一个Object数组对象,而这个object又是一个object[]数组。数组的元素是Employee和Dept类型的

6.2.迫切连接(fetch)方式返回的object[]的元素是具体的类型,关联的对象封装在该类型中

迫切连接,会把关联对象封装在对象中,list返回的object数组,数组的元素就只是一个对象,关联对象在该对象中

HQL优化:
1.将语句写到配置中:但是注意一下特殊符号的转义

配置语句:

改为:(小于号用<代替)

也可以改为:

实例代码:
Dept.java
public class Dept { private int deptId; private String deptName; // 【一对多】 部门对应的多个员工 private Set<Employee> emps = new HashSet<Employee>(); public Dept(int deptId, String deptName) { super(); this.deptId = deptId; this.deptName = deptName; } public Dept() { super(); }
Dept.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <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>
Employee.java
public class Employee { private int empId; private String empName; private double salary; // 【多对一】员工与部门 private Dept dept;;
Employee.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <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(0, 10); System.out.println(q.list()); session.getTransaction().commit(); session.close(); }
criteria/ SQLQuery 查询方式:
criteria查询:
局限是没有HQL灵活,比如聚合/统计

SQLQuery本地查询查询:

可以返回指定类型的数组
测试类:
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("empId", 12)); // 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(); }
查询总结:
1) Get/load主键查询 2) 对象导航查询 3) HQL查询, Hibernate Query language hibernate 提供的面向对象的查询语言。 4) Criteria 查询, 完全面向对象的查询(Query By Criteria ,QBC) 5) SQLQuery, 本地SQL查询 缺点: 不能跨数据库平台: 如果该了数据库,sql语句有肯能要改 使用场景: 对于复杂sql,hql实现不了的情况,可以使用本地sql查询。
hibernate提供了专门的分页查询:
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(); // 滚动到最后一行 int totalCount = scroll.getRowNumber() + 1;// 得到滚到的记录数,即总记录数 // 设置分页参数 q.setFirstResult(0); q.setMaxResults(3); // 查询得到是0-3的纪录 System.out.println(q.list()); System.out.println("总记录数:" + totalCount); session.getTransaction().commit(); session.close(); }
二、hibernate对连接池的支持
连接池:
作用: 管理连接;提升连接的利用效率!
常用的连接池: C3P0连接池
Hibernate 自带的也有一个连接池,且对C3P0连接池也有支持!
自带连接池:
只维护一个连接,比较简陋。
可以查看hibernate.properties文件查看连接池详细配置:
hibernate关于连接池配置参数:

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 空闲测试时间(数据库对对大概8小时空闲连接自动进行关闭,为了避免这种情况,hibernate会间隔时间发送一个空语句) #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配置文件,二级缓存如何配置?
#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)指定那些类加入二级缓存
<!--****************** 【二级缓存配置】****************** --> <!-- 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"/>
4)测试二级缓存!
// a. 查询一次 Dept dept = (Dept) session1.get(Dept.class, 10);//这里不仅保持到session缓存中,(设置了二级缓存)还保存在二级缓存 session1.getTransaction().commit(); session1.close(); // 第二个session Session session2 = sf.openSession(); session2.beginTransaction(); // a. 查询一次 dept = (Dept) session2.get(Dept.class, 10); // 二级缓存配置好; 另外的session,这里不查询数据库,从二级缓存取 //如果配置usage=“read-only”只读的,那么dept.setName("修改名字"),就会报错,从二级缓存取出的不能修改。
session2.getTransaction().commit(); session2.close();
补充:缓存策略
<class-cache usage="read-only"/> 放入二级缓存的对象,只读; <class-cache usage="nonstrict-read-write"/> 非严格的读写 <class-cache usage="read-write"/> 读写; 放入二级缓存的对象可以读、写; <class-cache usage="transactional"/> (3.x版本不支持,基于事务的策略)
集合缓存:
对于集合进行二级缓存,需要将集合的元素的类型对应的类也要进行缓存,(collection的属性值是要缓存的那个集合属性名)
<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"/>
另外一种写法,在映射中配置二级缓存(一般不采用,配置分散,不易维护):

测试:
// a. 查询一次 Dept dept = (Dept) session1.get(Dept.class, 10);//查询数据库,保存到session和二级缓存中 dept.getEmps().size();// 查询数据库,集合,会保存到二级缓存中 session1.getTransaction().commit(); session1.close();// 第二个session Session session2 = sf.openSession(); session2.beginTransaction(); // 下面都从二级缓存中取 dept = (Dept) session2.get(Dept.class, 10); // 二级缓存配置好; 这里不查询数据库 dept.getEmps().size();//从二级缓存中取
查询缓存(针对list方法):
list() 默认情况只会放入缓存,不会从一级缓存中取!
使用查询缓存,可以让list()查询从二级缓存中取!
使用查询缓存需要两个地方设置:
1.配置文件:(注意该配置标签的位置,放在类和集合缓存标签的前面)
<!-- 开启查询缓存 --> <property name="hibernate.cache.use_query_cache">true</property>
2.代码中需要指明是采用查询缓存(setCachable(true)
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(); }
配置的综合:
连接池,二级缓存(hibernate.cfg.xml)
<!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节点代表一个数据库 --> <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>
session的管理方式
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已经关闭了! }
补充(其他来源:)
hibernate 自身提供了 3种管理Session 对象的方法
①. Session 对象的生命周期与本地线程绑定
②. Session 对象的生命周期与JTA 事务绑定
③. Hibernate 委托程序管理Session 对象的生命周期
在 Hibernate 的配置文件中 hibernate.current_session_context_class 属性用于指定Session 管理方式,可选值包括3种
①.thread: Session 对象的生命周期与本地线程绑定 ②. jta*: Session 对象的生命周期与JTA 事务绑定 ③. managed: Hibernate 委托程序管理Session 对象的生命周期
优先选择1。
以第一种为例配置Hibernate 如何session 的管理步骤:
①. 在Hibernate 的配置文件hibernate.cfg.xml 中配置
<!-- 配置管理session 的方式 --> <property name="hibernate.current_session_context_class">thread</property>
②. 创建管理session 的类HibernateUtils.java
public class HibernateUtils { //hibernate的构造器 public HibernateUtils(){} //获取Hibernte的单实例 private static HibernateUtils instance = new HibernateUtils(); public static HibernateUtils getInstance(){ return instance; } //获取sessionFactory private SessionFactory sessionFactory; public SessionFactory getSessionFaction(){ if(sessionFactory == null){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } return sessionFactory; } // 通过getCurrentSession() 可以把 session和 当前线程绑定 :Current 的意思是:当前的 public Session getSession(){ return getSessionFaction().getCurrentSession(); } }
原理:

测试类:
@Test public void testHibernateManageSession(){ //获取session //开启事务 Session session = HibernateUtils.getInstance().getSession(); System.out.println("-->" + session.hashCode()); Transaction transaction = session.beginTransaction(); DepartmentDAO departmentDAO = new DepartmentDAO(); Department dept = new Department(); dept.setName("ChuckHero"); departmentDAO.save(dept); departmentDAO.save(dept); departmentDAO.save(dept); //若 Session 是由 thread 来管理的,则 在提交或回滚事务后,就 已经关闭Session System.out.println( "session.isOpen()1: " + session.isOpen()); transaction.commit(); System.out.println( "session.isOpen()2: " + session.isOpen()); }
结果:
-->852989707 session.hashCode: 852989707 Hibernate: select user_deptid.nextval from dual session.hashCode: 852989707 session.hashCode: 852989707 session.isOpen()1: true Hibernate: insert into BB_DEPARTMENTS (NAME, ID) values (?, ?) session.isOpen()2: false

浙公网安备 33010602011771号