2 xuxiaoyinliu xuxiaoyinliu 于 2016.02.03 10:08 提问

MyBatis与Spring整合后为什么使用flushCache无效? 5C

代码这样,为什么调用两次这个方法该SQL只会执行一次?

 @CacheNamespace(implementation=PerpetualCache.class)
public interface MapperDao {
    @Select("SELECT * FROM N1 WHERE ID=#{id}")
    @Options(useCache=true ,flushCache=true)
    public Cost getById(@Param("id") Integer id);
}

8个回答

rui888
rui888   Ds   Rxr 2016.02.03 10:24

flushCache=true 按道理是 会强制清空的。 你这个 useCache=true 这个不加看看会不会执行2次。
或者其他什么原因

xuxiaoyinliu
xuxiaoyinliu 好像这个参数无效了
接近 2 年之前 回复
xuxiaoyinliu
xuxiaoyinliu   2016.02.03 10:30

只要useCache=true不管flushCache=true还是false结果都是这样
日志:

 第1次:
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - Creating SqlSession with JDBC Connection [jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver]
DEBUG [main] - ooo Connection Opened
DEBUG [main] - JDBC Connection [jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@28cda624] was not registered for synchronization because synchronization is not active
DEBUG [main] - Cache Hit Ratio [com.dingxintec.dao.MapperDao]: 0.0
DEBUG [main] - ==>  Executing: SELECT * FROM N1 WHERE ID=? 
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <==    Columns: id, name, age
DEBUG [main] - <==        Row: 2, JACKSON, 99
DEBUG [main] - Closing no transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@28cda624]
DEBUG [main] - Returning JDBC Connection to DataSource
Cost [id=2, age=99, name=JACKSON, base_duration=null, base_cost=null, unit_cost=null, status=null, descr=null, startime=null, creatime=null, cost_type=null]
第2次:
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - Creating SqlSession with JDBC Connection [jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver]
DEBUG [main] - ooo Connection Opened
DEBUG [main] - JDBC Connection [jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7283d3eb] was not registered for synchronization because synchronization is not active
DEBUG [main] - Cache Hit Ratio [com.dingxintec.dao.MapperDao]: 0.5
DEBUG [main] - Closing no transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7283d3eb]
DEBUG [main] - Returning JDBC Connection to DataSource
Cost [id=2, age=99, name=JACKSON, base_duration=null, base_cost=null, unit_cost=null, status=null, descr=null, startime=null, creatime=null, cost_type=null]
DEBUG [main] - After test method: context [[TestContext@48140564 testClass = TestSpringMyBatis, testInstance = com.dingxintec.test.TestSpringMyBatis@58ceff1, testMethod = test@TestSpringMyBatis, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@7c30a502 testClass = TestSpringMyBatis, locations = '{classpath:applicationContext.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], class dirties context [false], class mode [null], method dirties context [false].
DEBUG [main] - After test class: context [[TestContext@48140564 testClass = TestSpringMyBatis, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@7c30a502 testClass = TestSpringMyBatis, locations = '{classpath:applicationContext.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], dirtiesContext [false].
 INFO [Thread-0] - Closing org.springframework.context.support.GenericApplicationContext@7a5d012c: startup date [Wed Feb 03 10:28:18 CST 2016]; root of context hierarchy
DEBUG [Thread-0] - Returning cached instance of singleton bean 'ssf'
DEBUG [Thread-0] - Returning cached instance of singleton bean 'lifecycleProcessor'
 INFO [Thread-0] - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@77ec78b9: defining beans [dbcp,ssf,mapperScanner,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,mapperDao]; root of factory hierarchy
DEBUG [Thread-0] - Retrieved dependent beans for bean '(inner bean)#9': [org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0]
DEBUG [Thread-0] - Retrieved dependent beans for bean '(inner bean)#1': [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0]
DEBUG [Thread-0] - Retrieved dependent beans for bean 'mapperDao': [com.dingxintec.test.TestSpringMyBatis]
DEBUG [Thread-0] - Retrieved dependent beans for bean '(inner bean)': [org.springframework.web.servlet.handler.MappedInterceptor#0]
rui888
rui888   Ds   Rxr 2016.02.03 10:40

useCache=true 和 flushCache=true 都不加 测试看看,怀疑你上层的方法有缓存 ,可能和你现在 useCache=true 和 flushCache=true 这个没有关系 。

xuxiaoyinliu
xuxiaoyinliu 都不加结果还是一样,这时应用的应该就是默认的useCache=true ,flashCache=false
接近 2 年之前 回复
rui888
rui888   Ds   Rxr 2016.02.03 10:52

你 的xml里面是不是也配置了,你看看着个

xuxiaoyinliu
xuxiaoyinliu 这个没有,我只在DAO接口中使用的标记
接近 2 年之前 回复
xuxiaoyinliu
xuxiaoyinliu   2016.02.03 11:17

唯一的配置文件

 <?xml version="1.0" encoding="UTF-8"?>
<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:util="http://www.springframework.org/schema/util"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 连接池 -->
<bean id="dbcp" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="username" value="root"></property>
  <property name="password" value="1234"></property>
  <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
  <property name="url" value="jdbc:mysql:///test?useUnicode=true&amp;characterEncoding=utf-8"></property>
</bean>
<!-- 封装了获取SqlSessionFactory对象的过程   -->

<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"> 
   <!-- 注入连接参数 -->
 <property name="dataSource" ref="dbcp" ></property><!-- 注入连接池参数 -->
   <!-- 注入SQL定义XML文件信息:当Mapper文件与对应的Mapper接口处于同一位置时可以不指定这个属性的值 -->
<!--  <property name="mapperLocations" value="classpath:org/tarena/mapper/*.xml"></property> -->
</bean>

<!-- 批量生成:配置MapperScannerConfigurer以扫描包路径方式批量生成Mapper接口实现 -->
  <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <!-- basePackage名称固定 -->
    <property name="basePackage" value="com.dingxintec.dao"></property>

  </bean>

<mvc:annotation-driven></mvc:annotation-driven>
</beans>
xuxiaoyinliu
xuxiaoyinliu 回复无法显示此用户:请问如何在spring中测试二级缓存是否开启了?我怀疑有什么地方配置有问题
接近 2 年之前 回复
xuxiaoyinliu
xuxiaoyinliu 回复无法显示此用户: 谢谢,你用过如何将Mybatis与Redis集成吗?我按照http://www.tuicool.com/articles/quqmy2个方法做了一遍但是一直有反射异常
接近 2 年之前 回复
rui888
rui888 想不出来哪里出现问题
接近 2 年之前 回复
Yiran8935
Yiran8935   2016.02.03 15:08

http://backend.blog.163.com/blog/static/202294126201352904327876/
看下这个如果把你的useCache="false"设置下看能不能达到你说的那个结果。

xuxiaoyinliu
xuxiaoyinliu useCache这个参数是没有问题的,只是flushCache这个参数不管用了,测试发现如果不用spring的话这个参数是可以正常运行的
接近 2 年之前 回复
xuxiaoyinliu
xuxiaoyinliu   2016.02.03 15:42

贴一下我的测试代码

 @Test
    public void test3(){
        String conf="applicationContext.xml";
        ApplicationContext ac=new ClassPathXmlApplicationContext(conf);
        SqlSessionFactory sf=ac.getBean("ssf",SqlSessionFactory.class);
        try {
            SqlSession session1=sf.openSession();
            SqlSession session3=sf.openSession();
            MapperDao dao1 = session1.getMapper(MapperDao.class);
            MapperDao dao3 = session3.getMapper(MapperDao.class);  
            System.out.println("session1第一次:");
            dao1.getById(2);
            session1.close();
            System.out.println("session3第一次:");
            dao3.getById(2);
            session3.close();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
xuxiaoyinliu
xuxiaoyinliu   2016.02.03 15:43

真心找不到原因了,明明flushCache=true了第二次查询还是会使用缓存

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!