Spring 整合 Hibernate 时启用二级缓存实例详解 Spring 整合 Hibernate 时启用二级缓存实例详解 写在前面:   1. 本例使用 Hibernate3 + Spring3;   2. 本例的查询使用了 HibernateTemplate; 1. 导入 ehcache-x.x.x.jar 包; 2. 在 applicationContext.xml 文件中找到 sessionFactory 相应的配置信息并在设置 hibernateProperties 中添加如下代码: true true org.hibernate.cache.EhCacheProvider 3. 由于查询使用了 hibernateTemplate,所以还要在 hibernateTemplate 中做相应配置,找到 hibernateTemplate 的配置项,添加如下代码: true 4. 在要缓存的实体类中加入如下注解: @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 注:   usage 可以有以下几个取值: CacheConcurrencyStrategy.NONE:不使用缓存,默认; CacheConcurrencyStrategy.READ_ONLY:只读模式,若对缓存的数据进行修改操作会抛出异常; CacheConcurrencyStrategy.NONSTRICT_READ_WRITE:不严格的读写模式,不会对缓存的数据加锁; CacheConcurrencyStrategy.READ_WRITE:读写模式,在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了,直接就去数据库查询; CacheConcurrencyStrategy.TRANSACTIONAL:事务模式,支持事务,当事务发生回滚时,缓存中的数据也回滚,只支持 JPA 。 5. 配置 ehcache.xml 文件: 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!