springmvc4-hibernate二级缓存应用

首先说明一下最初什么都不懂想用hibernate二级缓存的原因:手头项目是个商城网站,大量用户访问,就想到缓存

在经朋友推荐,初步看了以下二级缓存的功能,看似很符合需求,但是实际构建后,应用起来却发现并不是那么回事。但

既然已经了解了,不妨就稍微记下来。

hibernate二级缓存不适用项目的原因是因为它只能缓存通过id查询的实体(类)对象,而我们通常查询商品是通过使用

hql来查询带有较为复杂关联的对象,而并不是简单的通过id查询对象。所以在本次项目中,我没有使用,因为我发出十几条

查询语句,只有一句是通过Id来查询的,使用二级缓存就显得没有什么意义。


说明:

hibernate的二级缓存策略一般是这样,查询的时候我们发出hql或者是sql,里面通常是带where条件以及排序、分组参数的,

查询到结果以后,hibernate会把查询到的所有结果根据id存到二级缓存里。

然后当hibernate根据id访问数据对象的时候,会先去session一级缓存找,找不到,再去二级缓存里找,如果缓存里面都没有,

就去数据库查了。

因为二级缓存是针对id的,所以对于我们这种需要比较多条件动态参数组合的情景就显得没有什么用处


虽然没用,但是也要记下怎么做的。


项目类型:WebProject

项目环境:spring4.2.9-mvc、hibernate4.3.11.Final


我们需要到hibernate官方下载包,这里可以直接百度hibernate就可以。

我下载的是:hibernate-release-4.3.11.Final

是个压缩文件,解压后,hibernate-release-4.3.11.Final\lib\optional\ehcache

把上面的路径下的jar包导入项目中。


spring-xml文件:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>      
  2. <beans xmlns="http://www.springframework.org/schema/beans"          
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
  4.     xmlns:p="http://www.springframework.org/schema/p"        
  5.     xmlns:aop="http://www.springframework.org/schema/aop"         
  6.     xmlns:context="http://www.springframework.org/schema/context"        
  7.     xmlns:jee="http://www.springframework.org/schema/jee"        
  8.     xmlns:tx="http://www.springframework.org/schema/tx"        
  9.     xmlns:mvc="http://www.springframework.org/schema/mvc"        
  10.     xsi:schemaLocation="          
  11.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd        
  12.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd        
  13.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd        
  14.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd        
  15.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd          
  16.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">    
  17.     <!-- 引用properties文件里的配置  -->    
  18.     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    
  19.         <property name="locations">    
  20.             <list>    
  21.                 <value>classpath:config/setting.properties</value>    
  22.             </list>    
  23.         </property>    
  24.     </bean>    
  25.             
  26.     <!-- 启用@Resource功能 -->    
  27.     <context:annotation-config />    
  28.         
  29.     <!-- 启用@Repository、@Service、@Controller、@Component -->    
  30.     <context:component-scan base-package="cn.com.aa"/>    
  31.         
  32.     <!-- 配置数据源:jndi方式 -->    
  33.     <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">    
  34.         <property name="jndiName">    
  35.             <value>${jndiName}</value>    
  36.         </property>    
  37.     </bean>    
  38.         
  39.     <!-- annotation方式配置sessionFactory -->    
  40.     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">    
  41.         <property name="dataSource" ref="dataSource"/>    
  42.         <property name="packagesToScan" value="cn.com.aa"/>    
  43.         <property name="hibernateProperties">    
  44.             <props>    
  45.                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>    
  46.                 <strong><span style="color:#3366ff;"><prop key="hibernate.show_sql">true</prop><span style="white-space:pre">   </span><-- 这里是开启控制台输出hibernate向数据库发出sql的功能--></span></strong>  
[html]  view plain  copy
  1. <-- 这里是开启控制台输出hibernate向数据库发出sql的功能-->    
  2.                 <prop key="hibernate.format_sql">false</prop>    
  3.                 <!--  <prop key="hibernate.hbm2ddl.auto">update</prop>-->    
  4.                 <prop key="hibernate.jdbc.fetch_size">25</prop>    
  5.                 <!-- 没有下面的配置,在JUnit测试时会报错 -->    
  6.                 <prop key="javax.persistence.validation.mode">none</prop>    
  7.                 <!-- 开启缓存 -->    
  8.                 <prop key="hibernate.cache.use_query_cache">true</prop>    
  9.                 <!--开启二级缓存-->      
  10.                 <prop key="hibernate.cache.use_second_level_cache">true</prop>      
  11.                 <!--指定二级缓存的提供类-->      
  12.                 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>      
  13.                 <!--指定二级缓存配置文件的位置-->      
  14.                 <prop key="hibernate.cache.provider_configuration_file_resource_path">classpath:config/ehcache.xml</prop>      
  15.                 <!-- 强制Hibernate以更人性化的格式将数据存入二级缓存 -->      
  16.                 <prop key="hibernate.cache.use_structured_entries">true</prop>      
  17.                 <!-- Hibernate将收集有助于性能调节的统计数据 -->      
  18.                 <prop key="hibernate.generate_statistics">true</prop>      
  19.       
  20.             </props>    
  21.         </property>    
  22.     </bean>    
  23.         
  24.     <!-- 配置事务,使用spring自带的hibernate事务管理器 -->    
  25.     <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">    
  26.         <property name="sessionFactory" ref="sessionFactory"/>    
  27.     </bean>    
  28.     <tx:annotation-driven transaction-manager="txManager"/>    
  29.         
  30.     <!-- spring自带的hibernate工具类 -->     
  31.     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">    
  32.         <property name="sessionFactory" ref="sessionFactory"/>    
  33.     </bean>    
  34.         
  35.     <!--启动JSON格式的配置 -->    
  36.     <mvc:annotation-driven>    
  37.         <mvc:message-converters>    
  38.             <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
  39.                 <property name="supportedMediaTypes">    
  40.                     <list>    
  41.                          <value>text/plain;charset=utf-8</value>    
  42.                          <value>text/html;charset=UTF-8</value>    
  43.                          <value>text/json;charset=UTF-8</value>    
  44.                          <value>application/json;charset=utf-8</value>    
  45.                          <value>application/pdf;charset=ISO8859-1</value>    
  46.                              
  47.                    </list>    
  48.                 </property>    
  49.                 <property name="objectMapper">    
  50.                     <bean class="com.fasterxml.jackson.databind.ObjectMapper">    
  51.                         <property name="dateFormat">    
  52.                             <bean class="java.text.SimpleDateFormat">    
  53.                                 <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>    
  54.                             </bean>    
  55.                         </property>    
  56.                     </bean>    
  57.                 </property>    
  58.             </bean>    
  59.         </mvc:message-converters>    
  60.     </mvc:annotation-driven>    
  61.     
  62.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">      
  63.         <property name="messageConverters">      
  64.             <list>      
  65.                 <!-- 把ByteArray加在Json前面 -->      
  66.                 <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>      
  67.                 <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >      
  68.                     <property name = "supportedMediaTypes">      
  69.                         <list>      
  70.                             <value>application/json;charset=UTF-8</value>      
  71.                         </list>      
  72.                     </property>      
  73.                 </bean>      
  74.             </list>      
  75.         </property>      
  76.     </bean>    
  77.         
  78. </beans>      

配置完了之后,我们就进入我们的实体类。(我使用注解映射实体,不是用hibernate.xml配的)

[java]  view plain  copy
  1. /**  
  2.  * 管理员用户表  
  3.  */    
  4. @Entity    
  5. @Table(name="T_ADMIN_USER")    
  6. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)   //主要要加的就是这行注释了   
  7. public class AdminUser implements Serializable {    
  8.         
  9.     private static final long serialVersionUID = 1L;    
  10.     private String id;                  //主键    
  11.     private String loginName;           //用户名    
  12.     private String password;            //密码    
  13.     private Integer userType;           //用户类型    
  14.     private Date createTime;            //创建时间    
  15.     private String userName;            //用户真实姓名    
  16.     private String email;               //邮箱    
  17.     private String mobile;              //手机    
  18.     private Integer active;             //有效状态,1=有效(默认),0=无效    
  19.     private Integer delFlag;            //删除标识,0=可用(默认),1=已删除    
  20.     
  21.     public AdminUser() {    
  22.     
  23.     }    

然后如果有外键的话,也要加

@ManyToOne(fetch = FetchType.EAGER)
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@JoinColumn(name = "F_CLAUSE_ID", nullable = false)
public Clause getClause() {
return clause;
}

完成后,我是在dao的实现中添加的,由于有一个继承和实现的基础类和接口,所以我重写了其中的方法:

要是不写也有点效果,可以少点因为外键关联查询多发出的sql请求。

[java]  view plain  copy
  1. import org.hibernate.Session;    
  2. import org.hibernate.SessionFactory;    
  3. import org.springframework.beans.factory.annotation.Autowired;    
  4. import org.springframework.stereotype.Repository;    
  5.     
  6. import cn.com.aa.dao.ProductDao;    
  7. import cn.com.aa.entity.Product;    
  8.     
  9. @Repository("productDao")    
  10. public class ProductDaoHibernate extends GenericDaoHibernate<Product, String> implements    
  11.         ProductDao {    
  12.     
  13.     <span style="color:#ff6666;">@Autowired    
  14.     private SessionFactory sessionFactory;    
  15.     
  16.     private Session getCurrentSession() {    
  17.         return this.sessionFactory.getCurrentSession();    
  18.     }    
  19.         
  20.     @Override    
  21.     public Product findById(String id) {    
  22.         return (Product)this.getCurrentSession().get(Product.class, id);    
  23.     }</span>    
  24.         
  25. }    

这样就可以了。

我们可以打开hibernate的配置,在控制台输出hibernate发出的sql来查看是否缓存好了。


我们可以通过eclipse或者是MyEclipse的控制台看到,在我们前端第二次发起同一个请求的时候,

后台并没有像第一次前端发出请求时候,打出那个通过id查询的sql语句,说明hibernate进行数据库操作的时候,

使用了hibernate的二级缓存,所以没有从数据获取。

宁波眼部整形:http://www.iyestar.com/ybzx/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值