-----------------------------------------User.hbm.xml------------------------------------------------
<hibernate-mapping>
<class table="user" name="model.User">
<!-- 配置二级缓存 -->
<!--usage是缓存策略,read-only是user类是不会修改的,只读的。read-write是可以读写的-->
<cache usage="read-write"/>
<!-- unsaved-value="-1" 这个属性是用来判断是update或者save的。调用saveOrUpdate()方法时候用到 -->
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="userName" column="userName" not-null="true"/>
<property name="passWord" column="passWord" not-null="true"/>
</class>
</hibernate-mapping>
-----------------------------------------oscache.properties(此文件需要放到src目录下)---------------------
# CACHE IN MEMORY
#
# If you want to disable memory caching, just uncomment this line.
#
# cache.memory=false
# CACHE KEY
#
# This is the key that will be used to store the cache in the application
# and session scope.
#
# If you want to set the cache key to anything other than the default
# uncomment this line and change the cache.key
#
# cache.key=__oscache_cache
# USE HOST DOMAIN NAME IN KEY
#
# Servers for multiple host domains may wish to add host name info to
# the generation of the key. If this is true, then uncomment the
# following line.
#
# cache.use.host.domain.in.key=true
# CACHE LISTENERS
#
# These hook OSCache events and perform various actions such as logging
# cache hits and misses, or broadcasting to other cache instances across a cluster.
# See the documentation for further information.
#
# cache.event.listeners=com.opensymphony.oscache.plugins.clustersupport.JMSBroadcastingListener, \
# com.opensymphony.oscache.extra.CacheEntryEventListenerImpl, \
# com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl, \
# com.opensymphony.oscache.extra.ScopeEventListenerImpl, \
# com.opensymphony.oscache.extra.StatisticListenerImpl
# CACHE PERSISTENCE CLASS
#
# Specify the class to use for persistence. If you use the supplied DiskPersistenceListener,
# don't forget to supply the cache.path property to specify the location of the cache
# directory.
#
# If a persistence class is not specified, OSCache will use memory caching only.
#
# cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener
# cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener
# CACHE OVERFLOW PERSISTENCE
# Use persistent cache in overflow or not. The default value is false, which means
# the persistent cache will be used at all times for every entry. true is the recommended setting.
#
# cache.persistence.overflow.only=true
# CACHE DIRECTORY
#
# This is the directory on disk where caches will be stored by the DiskPersistenceListener.
# it will be created if it doesn't already exist. Remember that OSCache must have
# write permission to this directory.
#
# Note: for Windows machines, this needs \ to be escaped
# ie Windows:
# cache.path=c:\\myapp\\cache
# or *ix:
# cache.path=/opt/myapp/cache
#
# cache.path=c:\\app\\cache
# CACHE ALGORITHM
#
# Default cache algorithm to use. Note that in order to use an algorithm
# the cache size must also be specified. If the cache size is not specified,
# the cache algorithm will be Unlimited cache.
#
# cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache
# cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache
# cache.algorithm=com.opensymphony.oscache.base.algorithm.UnlimitedCache
# THREAD BLOCKING BEHAVIOR
#
# When a request is made for a stale cache entry, it is possible that another thread is already
# in the process of rebuilding that entry. This setting specifies how OSCache handles the
# subsequent 'non-building' threads. The default behaviour (cache.blocking=false) is to serve
# the old content to subsequent threads until the cache entry has been updated. This provides
# the best performance (at the cost of serving slightly stale data). When blocking is enabled,
# threads will instead block until the new cache entry is ready to be served. Once the new entry
# is put in the cache the blocked threads will be restarted and given the new entry.
# Note that even if blocking is disabled, when there is no stale data available to be served
# threads will block until the data is added to the cache by the thread that is responsible
# for building the data.
#
# cache.blocking=false
# CACHE SIZE
#
# Default cache size in number of items. If a size is specified but not
# an algorithm, the cache algorithm used will be LRUCache.
#
cache.capacity=1000
# CACHE UNLIMITED DISK
# Use unlimited disk cache or not. The default value is false, which means
# the disk cache will be limited in size to the value specified by cache.capacity.
#
# cache.unlimited.disk=false
# JMS CLUSTER PROPERTIES
#
# Configuration properties for JMS clustering. See the clustering documentation
# for more information on these settings.
#
#cache.cluster.jms.topic.factory=java:comp/env/jms/TopicConnectionFactory
#cache.cluster.jms.topic.name=java:comp/env/jms/OSCacheTopic
#cache.cluster.jms.node.name=node1
# JAVAGROUPS CLUSTER PROPERTIES
#
# Configuration properites for the JavaGroups clustering. Only one of these
# should be specified. Default values (as shown below) will be used if niether
# property is set. See the clustering documentation and the JavaGroups project
# (www.javagroups.com) for more information on these settings.
#
#cache.cluster.properties=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;\
#mcast_send_buf_size=150000;mcast_recv_buf_size=80000):\
#PING(timeout=2000;num_initial_members=3):\
#MERGE2(min_interval=5000;max_interval=10000):\
#FD_SOCK:VERIFY_SUSPECT(timeout=1500):\
#pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800;max_xmit_size=8192):\
#UNICAST(timeout=300,600,1200,2400):\
#pbcast.STABLE(desired_avg_gossip=20000):\
#FRAG(frag_size=8096;down_thread=false;up_thread=false):\
#pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=true)
#cache.cluster.multicast.ip=231.12.21.132
-----------------------------------------hibernate.cfg.xml------------------------------------------------
<session-factory>
<property name="connection.url">jdbc:mysql:///ssh</property>
<property name="connection.username">root</property>
<property name="connection.password">1</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 确定使用二级缓存 这个默认是true 可不配置-->
<property name="cache.use_second_level_cache">true</property>
<!-- 二级缓存由哪个类提供 一般使用OS缓存(还有其他的比如JBoss缓存、EH缓存等等) -->
<property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
<mapping resource="model/User.hbm.xml" />
<!-- 哪些类需要缓存 这是一种配置方法,还可以在映射文件配置
<class-cache usage="read-write" class="model.user"/> -->
</session-factory>
</hibernate-configuration>
------------------------------------------------applicationContext.xml------------------------------------------------
<!-- Session Factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<!-- Transaction 采用标注的形式加事务-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- HibernateDao -->
<bean id="hibernateDao" class="dao.impl.HibernateDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- Service -->
<bean id="springService" class="service.impl.SpringServiceImpl">
<property name="hibernateDao" ref="hibernateDao"></property>
</bean>
<!-- Action -->
<bean id="userAction" class="action.UserAction">
<property name="springService" ref="springService"></property>
</bean>
</beans>
------------------------------------------------web.xml------------------------------------------------
<!-- applicationContext.xml位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
--------------------------------------------------------------service代码---------------------------------------------------------------
package service.impl;
import java.util.List;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import dao.HibernateDao;
import model.User;
import service.SpringService;
public class SpringServiceImpl implements SpringService{
//注入hibernateDao
private HibernateDao hibernateDao;
//保存用户
@Transactional(propagation=Propagation.REQUIRED,rollbackFor={java.lang.Exception.class})
public void save(List<User> users) {
hibernateDao.save(users);
}
//更新
@Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="java.lang.Exception")
public void update(User user)
{
hibernateDao.update(user);
}
//删除
@Transactional(propagation=Propagation.REQUIRED,rollbackFor={java.lang.Exception.class})
public void delete(User user)
{
hibernateDao.delete(user);
}
//查找user
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public User findUserById(Integer id)
{
return hibernateDao.findUserById(id);
}
/**
* 注入HibernateDao
*/
public void setHibernateDao(HibernateDao hibernateDao) {
this.hibernateDao = hibernateDao;
}
}
---------------------------------------------------------Action-------------------------------------------------------------
package action;
import java.util.ArrayList;
import java.util.List;
import model.User;
import service.SpringService;
public class UserAction {
private SpringService springService;
private User user;
/**
* 默认执行方法
* @return 返回String
*/
public String execute()
{
List<User> list = new ArrayList<User>();
list.add(user);
springService.save(list);
return "success";
}
/**
* 测试缓存的,本来会应该有2条select语句,但是加了二级缓存后就只有一条了
*
*/
public String cache()
{
User user1 = springService.findUserById(1);
User user2 = springService.findUserById(1);
System.out.println(user1);
System.out.println(user2);
return "success";
}
/**
* 注入
*/
public void setSpringService(SpringService springService) {
this.springService = springService;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}