`
Vksnail
  • 浏览: 42342 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

hibernate2级缓存配置与测试

阅读更多
新建test项目→新建实体类Person→加入jar包
Person实体类代码:
@Entity
@Table(name = "person")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String name;
	private String age;
...略去get/set
}

Person.hbm.xml代码:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.test.cache">

	<class name="Person" table="person">
		<cache usage="read-write" />
		<id name="id" type="int">
			<generator class="increment" />
		</id>
		<property name="name" column="name" type="string"
			not-null="false" length="36" />

		<property name="age" column="age" type="string"
			length="100" />

	</class>
</hibernate-mapping>

操作步骤如下:::
第一步:加入到类路径下hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration  
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"  
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
<hibernate-configuration>  
    <session-factory>  
        <property name="connection.driver_class">  
            org.gjt.mm.mysql.Driver  
        </property>  
        <property name="connection.url">  
            jdbc:mysql://192.168.1.120:3306/test?useUnicode=true&amp;characterEncoding=utf-8  
        </property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">123456</property>  
  
        <property name="dialect">  
            org.hibernate.dialect.MySQLDialect  
        </property>
        <property name="connection.pool_size">10</property>  
        <property name="hibernate.jdbc.batch_size">10</property>  
  
        <property name="show_sql">true</property>  
        <property name="format_sql">true</property>  
        <property name="current_session_context_class">thread</property>  
        <property name="hbm2ddl.auto">none</property>  
              <property name="hibernate.cache.provider_class">  
           org.hibernate.cache.EhCacheProvider  
       </property>  
         
       <!-- Enable Second-Level Cache and Query Cache Settings -->  
       <property name="hibernate.cache.use_second_level_cache">  
           true  
       </property>  
       <property name="hibernate.cache.use_query_cache">  
           false  
       </property>  
 
       <!-- 注解配置  -->  
       <mapping class="com.test.cache.Person" />
       
       <!-- 映射文件 -->  
        <mapping  
            resource="com/test/cache/Person.hbm.xml" />  
    </session-factory>  
</hibernate-configuration>

第二步:测试一级缓存与二级缓存/查询缓存
1.测试一级缓存代码(get()方法/load()方法+second_level_cache=false,query_cache=false):
/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		SessionFactory sessionFactory = null;
		try {
			System.out.println("ehcache - hibernate Test ...");
			Configuration config = new AnnotationConfiguration()
					.configure("hibernate.cfg.xml");
			sessionFactory = config.buildSessionFactory();

			System.out.println("在同一个session中执行:::");
			Session session = sessionFactory.getCurrentSession();
			Transaction ta = session.beginTransaction();
			Person person = (Person) session.get(Person.class, 1);
			System.out.println(person.getName());

			System.out.println("第二次查询开始。。。。。");
			Person pern = (Person) session.get(Person.class, 1);
			ta.commit();
			System.out.println(pern.getName());
}

执行结果为:
ehcache - hibernate Test ...
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
在同一个session中执行:::
Hibernate:
    select
        person0_.id as id0_0_,
        person0_.name as name0_0_,
        person0_.age as age0_0_
    from
        person person0_
    where
        person0_.id=?
yf
第二次查询开始。。。。。
yf
sessionFactory  closed.
可以看出第二次执行未执行sql
2.测试2级级缓存代码(get()方法/load方法+second_level_cache=true,query_cache=false):
/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		SessionFactory sessionFactory = null;
		try {
			System.out.println("ehcache - hibernate Test ...");
			Configuration config = new AnnotationConfiguration()
					.configure("hibernate.cfg.xml");
			sessionFactory = config.buildSessionFactory();

			System.out.println("不在同一个session中执行======");
			Session session = sessionFactory.openSession();
			Transaction ta = session.beginTransaction();
			Person person = (Person) session.get(Person.class, 1);
			ta.commit();
			System.out.println(person.getName());

			System.out.println("第二次查询开始。。。。。");
			Session sess = sessionFactory.openSession();
			Transaction trans = session.beginTransaction();
			Person pern = (Person) sess.get(Person.class, 1);
			trans.commit();
			System.out.println(pern.getName());
}

执行结果为:
ehcache - hibernate Test ...
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
不在同一个session中执行======
Hibernate:
    select
        person0_.id as id0_0_,
        person0_.name as name0_0_,
        person0_.age as age0_0_
    from
        person person0_
    where
        person0_.id=?
yf
第二次查询开始。。。。。
yf
sessionFactory  closed.
可以看出第二次执行未执行sql
3.测试2级查询缓存(list()方法)+second_level=true,query_cache=false):
这种方式,query查询会缓存查询结果数据到2级缓存里,但是不会执行查询缓存
4.测试2级查询缓存(list()方法)+second_level=true,query_cache=true):
System.out.println("不在同一个session中执行list()======");
			Session session = sessionFactory.openSession();
			Transaction ta = session.beginTransaction();
			String hql = "select t from Person t where t.name='ryan'";
			Query que = session.createQuery(hql);
			que.setCacheable(true);
			System.out.println("list().size==" + que.list().size());
			ta.commit();

			System.out.println("第二次查询开始。。。。。");
			Session sess = sessionFactory.openSession();
			Transaction trans = session.beginTransaction();
			String shql = "select t from Person t where t.name='ryan'";
			Query query = sess.createQuery(shql);
			query.setCacheable(true);
			System.out.println("list().size==" + query.list().size());
			trans.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != sessionFactory) {
				sessionFactory.close();
			}
		}
		System.out.println("sessionFactory  closed.");
	}

执行结果:第二次查询并没有访问数据库,查询缓存使用hibernate生成的sql和参数生成缓存的key,再执行相同sql和相同条件的时候直接从缓存中去。
INFO org.hibernate.cache.UpdateTimestampsCache - starting update timestamps cache at region: org.hibernate.cache.UpdateTimestampsCache
INFO org.hibernate.cache.StandardQueryCache - starting query cache at region: org.hibernate.cache.StandardQueryCache
不在同一个session中执行list()======
Hibernate:
    select
        person0_.id as id0_,
        person0_.name as name0_,
        person0_.age as age0_
    from
        person person0_
    where
        person0_.name='ryan'
list().size==2
第二次查询开始。。。。。
list().size==2
INFO org.hibernate.impl.SessionFactoryImpl - closing
INFO org.hibernate.connection.DriverManagerConnectionProvider - cleaning up connection pool: jdbc:mysql://192.168.1.120:3306/test?useUnicode=true&characterEncoding=utf-8
sessionFactory  closed.
分享到:
评论

相关推荐

    EhCache_Hibernate二级缓存配置_详细

    本人在做项目时用到了Hibernate的二级缓存,使用的是EhCache,结合本人自己的理解总结了如何在java web项目中配合Hibernate使用二级缓存,以提高程序的性能,附带需要的文件,参考的文件,和测试类以及说明。

    hibernate基础教程

    第四步:编写测试类,体验Hibernate的二级缓存. 第五步:二级缓存的数据并发策略. 当我们使用二级缓存的时候,如果并发策略为:read-only,那么只能对持久化对象进行查询,不能对其进行修改.这...

    Hibernate环境配置与测试

    Hibernate管理的三种状态 Transient(瞬时态) 使用new关键字,没有持久化,没有缓存到Session中 Persistent (持久态) 特点:已经持久化,添加到Session缓存中 Detached(游离态 特点:已被持久化,但不在...

    Struts2 + Spring3 + Hibernate3.5 整合(集成测试配套jar包更新构建脚本使用说明)

    本版本全面更新了jar包,全部使用了当前最新版本的jar包,struct2.1.8 spring3 hibernate3.5,全面使用注解取代xm的l配置。 另外增加了一个ant构建脚本,支持使用hudson完成每日构建,持续集成,自动测试,代码规范...

    Struts2+Spring+Hibernate+Ehcache+AJAX+JQuery+Oracle 框架集成用户登录注册Demo工程

    5.单数据源配置(兼容Tomcat和Weblogic)。 6.Hibernate继承 HibernateDaoSupport。 7.Spring+Junit4单元测试,优点:不会破坏数据库现场,等等。 2)Demo 导入说明: 1.Eclipse Encoding:GBK 2.Eclipse 导入后可能...

    hibernate 体系结构与配置 参考文档(html)

    二级缓存与查询缓存 3.4.5. 查询语言中的替换 3.4.6. Hibernate的统计(statistics)机制 3.5. 日志 3.6. 实现NamingStrategy 3.7. XML配置文件 3.8. J2EE应用程序服务器的集成 3.8.1. 事务策略配置 3.8.2. ...

    Hibernate实战(第2版 中文高清版)

     2.1.3 Hibernate配置和启动   2.1.4 运行和测试应用程序   2.2 启动Java Persistence项目   2.2.1 使用Hibernate Annotations   2.2.2 使用Hibernate EntityManager   2.2.3 引入EJB组件   2.2.4 切换...

    Hibernate+中文文档

    3.5. Hibernate缓存属性 3.6. Hibernate事务属性 3.7. 其他属性 3.8. Hibernate SQL方言 (hibernate.dialect) 3.9. Hibernate日志类别 3.10. JTA TransactionManagers 9.1. 继承映射特性(Features of ...

    Struts2 + Spring3 + Hibernate3.5 整合(实际使用项目,version2)

    本版本全面更新了jar包,全部使用了当前最新版本的jar包,struct2.1.8 spring3 hibernate3.5,全面使用注解取代xm的l配置。 另外增加了一个ant构建脚本,支持使用hudson完成每日构建,持续集成,自动测试,代码规范...

    spring+springmvc+hibernate框架Demo

    其中包含apache的log4j记录日志信息,spring管理组件,springmvc分层,springaop配置数据库事务控制,hibernate二级缓存配置,实现了查询,用户登录注册,请求验证是否登录等基础功能Demo,基于后台测试,使用前台...

    HibernateAPI中文版.chm

    3.5. Hibernate缓存属性 3.6. Hibernate事务属性 3.7. 其他属性 3.8. Hibernate SQL方言 (hibernate.dialect) 3.9. Hibernate日志类别 3.10. JTA TransactionManagers 9.1. 继承映射特性(Features of ...

    hibernate3.2中文文档(chm格式)

    3.5. Hibernate缓存属性 3.6. Hibernate事务属性 3.7. 其他属性 3.8. Hibernate SQL方言 (hibernate.dialect) 3.9. Hibernate日志类别 3.10. JTA TransactionManagers 9.1. 继承映射特性(Features of ...

    Spring3.2_Hibernate4.2_JPA2全注解实例

    Spring3.2 Hibernate4.2 JPA2全注解实例.采用JTA事务管理,配置ehcache为二级缓存,在glassfish3.2.2和postgresql9测试通过。参考网上的资料整理。

    vip会员登录系统结合spring + mvc +hibernate

    其中包含apache的log4j记录日志信息,spring管理组件,springmvc分层,springaop配置数据库事务控制,hibernate二级缓存配置,实现了查询,用户登录注册,请求验证是否登录等基础功能Demo,基于后台测试,使用前台...

    hibernate+中文api

    3.4.4. 二级缓存与查询缓存 3.4.5. 查询语言中的替换 3.4.6. Hibernate的统计(statistics)机制 3.5. 日志 3.6. 实现NamingStrategy 3.7. XML配置文件 3.8. J2EE应用程序服务器的集成 3.8.1. 事务策略配置 ...

    Struts2 + Spring3 + Hibernate3.5 整合(实际使用项目,version3).part1

    本版本全面更新了jar包,全部使用了当前最新版本的jar包,struct2.1.8 spring3 hibernate3.5,全面使用注解取代xm的l配置。 另外增加了一个ant构建脚本,支持使用hudson完成每日构建,持续集成,自动测试,代码规范...

    Hibernate 中文 html 帮助文档

    3.4.4. 二级缓存与查询缓存 3.4.5. 查询语言中的替换 3.4.6. Hibernate的统计(statistics)机制 3.5. 日志 3.6. 实现NamingStrategy 3.7. XML配置文件 3.8. J2EE应用程序服务器的集成 3.8.1. 事务策略配置 ...

    Hibernate中文详细学习文档

    3.4.4. 二级缓存与查询缓存 3.4.5. 查询语言中的替换 3.4.6. Hibernate的统计(statistics)机制 3.5. 日志 3.6. 实现NamingStrategy 3.7. XML配置文件 3.8. J2EE应用程序服务器的集成 3.8.1. 事务策略配置 ...

    Hibernate_3.2.0_符合Java习惯的关系数据库持久化

    3.5. Hibernate缓存属性 3.6. Hibernate事务属性 3.7. 其他属性 3.8. Hibernate SQL方言 (hibernate.dialect) 3.9. Hibernate日志类别 3.10. JTA TransactionManagers 9.1. 继承映射特性(Features of ...

    hibernate-l2cache:使用 infinispan 测试 hibernate-l2cache

    这是 1. 如何使用 hibernate 2. 如何使用 Infinispan 配置 hibernate l2 缓存的示例 3. 如何配置 Infinispan 缓存 4. 如何使用 Infinispan Interceptors 项目使用 PostgreSQL 作为数据库。

Global site tag (gtag.js) - Google Analytics