`
Vksnail
  • 浏览: 43495 次
  • 性别: 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.
分享到:
评论

相关推荐

    Hibernate二级缓存

    3. **实体缓存配置**:接下来,在对应实体的映射文件(如`Customer.hbm.xml`)中,启用二级缓存支持。例如: ```xml ... ``` 这里的`usage`属性可以设置为`read-only`、`nonstrict-read-write`、`read-...

    Hibernate一级缓存、二级缓存以及查询缓存实例

    一级缓存的作用在于避免频繁地与数据库交互,提高效率。例如,当我们第一次从数据库加载一个实体后,再次请求该实体时,Hibernate会首先在一级缓存中查找,而不会去数据库查询,从而提高了性能。在实际项目中,合理...

    springboot+jpa(hibernate配置redis为二级缓存) springboot2.1.4

    在Spring Boot项目中配置Redis作为Hibernate的二级缓存,我们需要以下步骤: 1. **添加依赖**: 首先,在`pom.xml`文件中添加Spring Boot的JPA、Hibernate和Redis相关依赖,如: ```xml &lt;groupId&gt;org.spring...

    hibernate二级缓存(包括注解方式)

    例如,`@Cacheable`注解标记一个类为可缓存,`@Cache`注解可以进一步细化缓存配置,如区域、策略等。 5. **缓存区域**:在Hibernate中,可以创建多个缓存区域,每个区域可以有自己的缓存策略。例如,可以为经常读取...

    hibernate5.1二级缓存包

    2. **配置**:在 Hibernate 的配置文件(如 hibernate.cfg.xml)中启用二级缓存,并指定使用的缓存提供商。例如,如果使用 Ehcache,需要设置 `&lt;property name="hibernate.cache.use_second_level_cache"&gt;true...

    Hibernate二级缓存技术

    – 设置Hibernate缓存提供者为EhCache –&gt; &lt;property name="cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider &lt;!– 启用查询缓存 –&gt; &lt;property name="hibernate.cache.use_query_cache"&gt;true ``` 同时...

    hibernate二级缓存

    通过阅读和运行这个工程,开发者可以更好地理解和掌握Hibernate缓存的实践运用。 总之,理解并有效地使用Hibernate的缓存机制对于提升应用程序性能至关重要。一级缓存和二级缓存相辅相成,前者提供事务级别的高效...

    hibernate二级缓存使用范例

    在配置二级缓存时,我们需要在Hibernate的配置文件中声明缓存提供者,并在实体类的映射文件中启用二级缓存。例如,对于Ehcache,可以在`hibernate.cfg.xml`中添加以下配置: ```xml &lt;property name="hibernate....

    Hibernatehibernate二级缓存.pdf

    2. 在Hibernate配置文件(如hibernate.cfg.xml)中开启二级缓存,通过设置`&lt;property name="hibernate.cache.use_second_level_cache"&gt;true&lt;/property&gt;`。 3. 指定缓存提供商,例如`&lt;property name="hibernate.cache...

    J2EE企业级项目开发-1期 05 hibernate二级缓存实战经验.doc

    文档“J2EE企业级项目开发-1期 05 hibernate二级缓存实战经验.doc”探讨了Hibernate二级缓存的实战应用,这对于提高应用程序性能和减少对数据库的频繁访问至关重要。 **Hibernate二级缓存** 二级缓存是Hibernate...

    Hibernate缓存,性能优化

    - **二级缓存配置**:根据业务需求选择合适的缓存策略和过期机制,合理设置缓存区域,避免不必要的数据冗余和竞争,同时考虑数据一致性问题,确保缓存的有效性。 #### 优化查询和SQL语句 - **减少N+1查询问题**:...

    hibernate二级缓存相关插件(EHcache)

    3. **实体类缓存配置**:对于需要缓存的实体类,使用`@Cacheable`、`@Cache`等注解进行配置。例如: ```java @Entity @Table(name = "example_table") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) ...

    EhCache_Hibernate二级缓存配置_详细

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

    struts2+hibernate+ehcache二级缓存

    2. **配置Hibernate**:在`hibernate.cfg.xml`中启用二级缓存,并指定Ehcache为缓存提供者: ```xml &lt;property name="hibernate.cache.region.factory_class"&gt;org.hibernate.cache.ehcache.EhCacheRegionFactory ...

    使用Hazelcast迁移hibernate的二级缓存.docx

    总结来说,迁移Hibernate的二级缓存到Java 10环境需要处理JDK 10的模块化问题,适配新版本的Hibernate和Hazelcast,以及正确配置缓存设置。通过以上步骤,开发者可以确保在Java 10环境下,项目仍然能够充分利用...

    Hibernate缓存策略(一级缓存、二级缓存).docx

    如果在关闭Session后重新打开并尝试加载相同对象,Hibernate将不再能从一级缓存中获取,而是重新执行SQL查询,这就是第二个测试示例中出现多条SQL的原因。 二级缓存,又称为SessionFactory缓存,是可选的,跨事务的...

    Hibernate中二级缓存ehcache缓存案例

    在测试过程中,注意监控日志,查看是否有异常信息,以及缓存命中率、缓存读写操作等统计信息,以便优化缓存配置。 总之,理解和掌握Hibernate中的二级缓存ehcache对于提高Java应用的性能至关重要。正确配置和使用...

    hibernate以及连接池

    1. EhCache:EhCache是Hibernate默认的二级缓存提供商,支持本地内存缓存和分布式缓存,可配置缓存策略,如定时刷新、大小限制等。 2. Guava Cache:Google的Guava库提供了缓存功能,可以集成到Hibernate中作为二级...

    hibernate-level2-cache:在Hibernate 2级缓存上进行测试

    在Java的持久化框架Hibernate中,二级缓存(Level 2 Cache)是一个非常重要的特性,它能够显著提高应用性能,减少数据库的访问压力。本文将深入探讨Hibernate的二级缓存,包括其工作原理、配置、优缺点以及如何在...

Global site tag (gtag.js) - Google Analytics