测试hibernate的二级缓存(二)

来源:互联网 发布:网络弱电系统图图解 编辑:程序博客网 时间:2024/06/07 05:57

hibernate的二级缓存的测试类:

package com.echo.cache2;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;/** * 测试二级缓存 *  * @author Administrator *  */public class Testhibernate {public static void main(String[] args) {SessionFactory sessionFactory = mySessionFactory();// 打开会话Session1Session session1 = sessionFactory.openSession();// 3.开启事务Transaction transaction1 = session1.beginTransaction();Course c1 = (Course)session1.load(Course.class, 1);System.out.println(c1.getCourName()+"====");// 5.提交事务transaction1.commit();// 6.关闭session1session1.close();// 打开会话Session2Session session2 = sessionFactory.openSession();// 3.开启事务Transaction transaction2 = session2.beginTransaction();Course c2 = (Course)session2.load(Course.class, 1);System.out.println(c2.getCourName()+"----");// 5.提交事务transaction2.commit();// 6.关闭session2session2.close();sessionFactory.close();}public static SessionFactory mySessionFactory() {SessionFactory sessionFactory = null;// 读取并解析配置文件hibernate.cfg.xmlConfiguration configuration = new Configuration().configure();// configuration.addClass(Course.class);ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();/* * 读取并解析映射文件*.hbm.xml, * 通过Configuration类的buildSessionFactory(serviceRegistry)方法实现, * 同时该方法将返回一个会话工厂SessionFactory。 */sessionFactory = configuration.buildSessionFactory(serviceRegistry);return sessionFactory;}}

测试结果为:

Hibernate:     select        course0_.courId as courId1_0_0_,        course0_.courTime as courTime2_0_0_,        course0_.courName as courName3_0_0_,        course0_.credit as credit4_0_0_,        course0_.stid as stid5_0_0_     from        student.course course0_     where        course0_.courId=?张三====张三----

原因分析:第一次从数据库select放到二级缓存。第二次直接从二级缓存中取。


如果没有使用二级缓存,则输出的测试结果为:

Hibernate:     select        course0_.courId as courId1_0_0_,        course0_.courTime as courTime2_0_0_,        course0_.courName as courName3_0_0_,        course0_.credit as credit4_0_0_,        course0_.stid as stid5_0_0_     from        student.course course0_     where        course0_.courId=?张三====Hibernate:     select        course0_.courId as courId1_0_0_,        course0_.courTime as courTime2_0_0_,        course0_.courName as courName3_0_0_,        course0_.credit as credit4_0_0_,        course0_.stid as stid5_0_0_     from        student.course course0_     where        course0_.courId=?张三----


0 0
原创粉丝点击