一级缓存:session级别
二级缓存:sessionFactory级别
查询缓存:相同的SQL语句,不再重复执行
默认情况下,hibernate已经支持一级缓存了。
要支持二级缓存,步骤如下:
在spring配置文件applicationContext.xml中加入下面配置:
<!-- cache manager --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="shared" value="true" /> <property name="configLocation" value="classpath:ehcache.xml" /> </bean> <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager" ref="cacheManager" /> <property name="cacheName" value="root" /> </bean>
同时需要在hibernate的配置文件hibernate.cfg.xml中添加下面配置(下面包括了查询缓存和二级缓存):
<!-- use query cache --> <property name="hibernate.cache.use_query_cache">true</property> <!-- user second level cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
以及ehcache.xml(ehcache自身的配置文件):
<?xml version="1.0" encoding="UTF-8" ?> <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="3600" maxElementsInMemory="10000" overflowToDisk="true"> </defaultCache> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="50" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="false" /> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="false" /> </ehcache>
另外,假如我们需要对User这个类进行缓存,需要加下面注解:@cache ,如果映射方式是通过xml的方式的话,需要用另外的方式,这里就不多说了
package com.tch.test.ssh.entity.annotation; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * User entity. @author MyEclipse Persistence Tools */ @Entity @Table(name="user") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class User implements java.io.Serializable { // Fields private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; private String password; //private Set<Priority> priorities; // Constructors @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + "]"; } /** default constructor */ public User() { } /** full constructor */ public User(String name, String password) { this.name = name; this.password = password; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
然后就可以使用了:
假如我们页面有个地方,多次调用了Dao层的一个load方法:
public void load() { User u = (User) getSession().load(User.class, 2); System.out.println(u); }
那么就会发现,多次调用该方法,但是执行的SQL语句,只执行了一次,没有多次执行,这就表明二级缓存起作用啦。
注意,session 的 load方法会使用缓存,但是query 的 list 方法只会往缓存中放数据,不会从缓存取数据,所以使用list是不行的,会发出多次SQL语句
要解决list的缓存问题,就用到了下面的查询缓存了。
查询缓存:解决相同SQL语句的多次执行问题,注意,SQL语句不同的话,是不能使用二级缓存和查询缓存的。
同时,查询缓存依赖于二级缓存,所以需要配置二级缓存:
<!-- use query cache --> <property name="hibernate.cache.use_query_cache">true</property> <!-- use second level cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
其它的同二级缓存,但是需要额外添加的操作就是,在query的list操作之前,需要调用setCacheable(true) :
session.createQuery(hql).setCacheable(true).list();
这样就可以实现相同SQL语句的查询缓存了。
下面贴上部分代码:
applicationContext.xml :
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 启动注入功能 --> <context:annotation-config /> <!-- 启动扫描component功能 --> <context:component-scan base-package="com.tch.test.ssh" /> <!-- 启动注解实物配置功能 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!--读取数据库配置文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="mappingLocations"> <list> <!-- <value>classpath*:com/tch/test/ssh/entity/*.hbm.xml</value> --> </list> </property> <property name="packagesToScan"> <list> <value>com.tch.test.ssh.entity.annotation</value> </list> </property> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean> <!-- cache manager --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="shared" value="true" /> <property name="configLocation" value="classpath:ehcache.xml" /> </bean> <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager" ref="cacheManager" /> <property name="cacheName" value="root" /> </bean> </beans>
ehcache.xml :
<?xml version="1.0" encoding="UTF-8" ?> <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" maxElementsInMemory="10000" overflowToDisk="true"> </defaultCache> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="50" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="false" /> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="false" /> </ehcache>
hibernate.cfg.xml :
<?xml version='1.0' encoding='utf-8'?> <!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> <property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property> <property name="hibernate.proxool.xml">proxool.xml</property> <property name="hibernate.proxool.pool_alias">local_proxool</property> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="current_session_context_class">thread</property> <!-- use query cache --> <property name="hibernate.cache.use_query_cache">true</property> <!-- use second level cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration>
proxool.xml (数据库连接池的配置,和本文无关):
<?xml version="1.0" encoding="UTF-8"?> <something-else-entirely> <proxool> <alias>local_proxool</alias> <driver-url>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull</driver-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <driver-properties> <property name="user" value="root"/> <property name="password" value="root"/> </driver-properties> <house-keeping-sleep-time>90000</house-keeping-sleep-time> <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql> <prototype-count>4</prototype-count> <simultaneous-build-throttle>50</simultaneous-build-throttle> <maximum-connection-count>300</maximum-connection-count> <minimum-connection-count>2</minimum-connection-count> <maximum-connection-lifetime>3600000</maximum-connection-lifetime> </proxool> </something-else-entirely>
struts.xml :(个人测试使用的SSH的项目)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="show" class="userAction" method="show"> <result>/WEB-INF/pages/User.jsp</result> </action> <action name="load" class="userAction" method="load"> <result>/WEB-INF/pages/User.jsp</result> </action> </package> </struts>
其中后台的load对应的action最终调用的DAO层的load方法:
@Override public void load() { User u = (User) getSession().load(User.class, 2); System.out.println(u); }
多次调用该方法,会发现,只执行了一次SQL,这就是缓存的作用啦
后台的show对应的action最终调用的DAO层的show方法:
@Override public List show() { return getSession().createQuery("from User").setCacheable(true).list(); }
其中User类:
package com.tch.test.ssh.entity.annotation; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * User entity. @author MyEclipse Persistence Tools */ @Entity @Table(name="user") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class User implements java.io.Serializable { // Fields private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; private String password; //private Set<Priority> priorities; // Constructors @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + "]"; } /** default constructor */ public User() { } /** full constructor */ public User(String name, String password) { this.name = name; this.password = password; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
好了,不早了,睡觉。。。