mybatis增删改到底会不会刷新一级缓存?

qq_29073193 2017-03-10 09:18:20
测试代码:

public class MyTest {

private StudentDao studentDao;
private SqlSession sqlSession;

@Before
public void before(){
sqlSession = MyBatisUtils.getSqlSession();
studentDao = sqlSession.getMapper(StudentDao.class);//通过接口名 生成动态代理对象
/*将映射文件中<mapper/>标签的 namespace 属性设为 Dao 接口的全类名,则系统会根据方法所属 Dao 接口,
* 自动到相应 namespace 的映射文件中查找相关的 SQL 映射*/
}

@After
public void after(){
if(sqlSession!=null){
sqlSession.close();
}
}

@Test
public void testInsertStudent(){
Student student = studentDao.selectStudentById(5);
System.out.println(student);

Student student1 = new Student("小夏日", 14, 78.5);
studentDao.insertStudent(student1);
System.out.println("=============================");


Student student3 = studentDao.selectStudentById(5);
System.out.println(student3);
}
}



运行结果:[DEBUG] ==> Preparing: select id,name,age,score from student where id=?
[DEBUG] ==> Parameters: 5(Integer)
[TRACE] <== Columns: id, name, age, score
[TRACE] <== Row: 5, 张三, 23, 83.00
[DEBUG] <== Total: 1
Student [id=5, name=张三, age=23, score=83.0]
[DEBUG] ==> Preparing: insert into student(name,age,score) values(?,?,?)
[DEBUG] ==> Parameters: 小夏日(String), 14(Integer), 78.5(Double)
=============================
Student [id=5, name=张三, age=23, score=83.0]



这是我测试代码,如果增删改能刷新缓存,应该可以看到两个sql查询语句,为啥我只有一个

而且更匪夷所思的是我根本没有提交,插入的数据还能写入数据库,到底怎么回事,求大神解释
...全文
428 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
李德胜1995 2017-03-11
  • 打赏
  • 举报
回复 1
引用 4 楼 qq_29073193 的回复:
我发现问题了,我用的select标签执行的插入语句,没提交就可以直接插进去了,默认不刷新缓存;改用insert标签后一切都恢复正常了。奇怪的是用select标签执行插入竟然还能插进去,真想不到
你sqlSessionFactory.openSession(false);要设置不自动提交,然后写个异常看会不会回滚,如果没有回滚,估计就是没有配置事务管理器
qq_29073193 2017-03-10
  • 打赏
  • 举报
回复
我发现问题了,我用的select标签执行的插入语句,没提交就可以直接插进去了,默认不刷新缓存;改用insert标签后一切都恢复正常了。奇怪的是用select标签执行插入竟然还能插进去,真想不到
qq_29073193 2017-03-10
  • 打赏
  • 举报
回复
谢谢,试了一些确实跟你说的一样,但为什么我没调用sqlSession.commit();为什么数据都能插入数据库中呢?
李德胜1995 2017-03-10
  • 打赏
  • 举报
回复
flushCache="true"可以设置是否刷新一级缓存。。。默认不刷新
qq_29073193 2017-03-10
  • 打赏
  • 举报
回复
这是我的映射文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.sxt.dao.StudentDao"> <select id="selectStudentById" parameterType="cn.sxt.beans.Student" resultType="Student"> select id,name,age,score from student where id=#{id} </select> <select id="selectStudentById2" parameterType="Student" resultType="Student"> select id,name,age,score from student where id=#{id} </select> <select id="insertStudent" parameterType="Student" resultType="Student"> insert into student(name,age,score) values(#{name},#{age},#{score}) </select> </mapper>

67,549

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧