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查询、连接池、二级缓存的更多相关文章

  1. hibernate对连接池的支持和HQL查询

    hibernate对连接池的支持 连接池, 作用: 管理连接:提升连接的利用效率! 常用的连接池: C3P0连接池 Hibernate 自带的也有一个连接池,且对C3P0连接池也有支持! 只维护一个连 ...

  2. hibernate框架学习之二级缓存(测试用例)

    HqlDemoApp.java package cn.itcast.h3.query.hql; import java.io.Serializable; import org.hibernate.Qu ...

  3. hibernate框架学习之二级缓存

    缓存的意义 l应用程序中使用的数据均保存在永久性存储介质之上,当应用程序需要使用数据时,从永久介质上进行获取.缓存是介于应用程序与永久性存储介质之间的一块数据存储区域.利用缓存,应用程序可以将使用的数 ...

  4. Java Hibernate 之连接池详解

    Hibernate支持第三方的连接池,官方推荐的连接池是C3P0,Proxool,以及DBCP.在配置连接池时需要注意的有三点: 一.Apche的DBCP在Hibernate2中受支持,但在Hiber ...

  5. java框架篇---hibernate之连接池

    Hibernate支持第三方的连接池,官方推荐的连接池是C3P0,Proxool,以及DBCP.在配置连接池时需要注意的有三点: 一.Apche的DBCP在Hibernate2中受支持,但在Hiber ...

  6. hibernate的一级和二级缓存

    一级缓存就是Session级别的缓存,close后就没了. 二级缓存就是SessionFactory级别的缓存,全局缓存,要配置其他插件. 什么样的数据适合存放到第二级缓存中? 1.很少被修改的数据 ...

  7. Hibernate 集成 Ehcache 开启二级缓存

    一.将 Ehcache.xml 放到 classpath 下 <?xml version="1.0" encoding="UTF-8"?> < ...

  8. hibernate对连接池的支持

    连接池, 作用: 管理连接:提升连接的利用效率! 常用的连接池: C3P0连接池   Hibernate 自带的也有一个连接池,且对C3P0连接池也有支持!   Hbm 自带连接池:          ...

  9. 【Hibernate】Hibernate系列7之二级缓存

    二级缓存 7.1.概述 7.2.配置方法

  10. Hibernate 性能优化之二级缓存

    二级缓存是一个共享缓存,在二级缓存中存放的数据是共享数据特性     修改不能特别频繁     数据可以公开二级缓存在sessionFactory中,因为sessionFactory本身是线程安全,所 ...

随机推荐

  1. [NEUQ-OJ] 1012 SZ斐波拉契数列

    一道水题,让我看清基础我的基础是多么薄弱. 递归,数组清零,数组名/变量名重复层出不穷...路漫漫啊.......... http://ncc.neuq.edu.cn/oj/problem.php?i ...

  2. Redis性能问题排查解决手册

    转自:http://www.cnblogs.com/mushroom/p/4738170.html 阅读目录: 性能相关的数据指标 内存使用率used_memory 命令处理总数total_comma ...

  3. 谈谈ThreadStatic

    可能经常做多线程.线程池的童鞋早就知道这种问题,原谅我一直对线程研究不深. 这个东西好像出现有一段时间了,不过最近我才用到,做的API的服务,用来保存当前请求的上下文内容,原来用过Thread.Set ...

  4. PHP 苹果消息推送

    /* * 苹果消息推送方法 * $deviceToken 苹果设备token * $message 消息内容 */ function iosmsg_send($deviceToken,$message ...

  5. cocos2d-js引擎学习笔记

    cocos2d-js3.0实用语法 /*初始化继承类*/ var Enemy = cc.Sprite.extend({ hp: 0, fileName: "enemy.png", ...

  6. 中小型公司数据仓库搭建——以mysql为例

    为了方便公司的数据分析平台的独立运行和数据挖掘的探索,今年上半年在公司搭建了支持数据平台和数据挖掘的数据仓库:现就数据仓库的创建工作总结如下,供大家参考: 首先介绍下数据仓库搭建的缘由: 公司创建两年 ...

  7. swift 图像的压缩上传

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [Str ...

  8. synchronized细节问题

    一.synchronized有锁重入的特点,某个线程得到对象的锁后,再次请求此对象可以再次得到改对象的锁.如下示例,在method1中调用method2,在method2中调用method3,而met ...

  9. 第三天 函数 三元运算 lambda表达式 内置函数 文件操作

    面向过程: 直接一行一行写代码,遇到重复的内容复制黏贴. 不利于代码阅读 代码没有复用 面向对象 将代码块定义为函数,以后直接调用函数 增强了复用性 函数的定义方法 def 函数名(传递参数): 函数 ...

  10. (十)foreac遍历、break和countinue以及标签和switch循环

    foreach语法,表示不必创建int变量去对由访问项构成的序列进行计数,foreach将自动产生每一项. 例:输出数组的所有元素. float f[]=new float[5]; f[0]=1.0f ...