MySQL中的查询事务问题

之前帮同学做个app的后台,使用了MySQL+MyBatis,遇到了一个查询提交的问题,卡了很久,现在有时间了来复盘下

环境情况

假设有学生表:

USE test;
CREATE TABLE `student` (
  Id int  NOT NULL PRIMARY KEY AUTO_INCREMENT,
  Name varchar(20) NOT NULL,
  Grade int NOT NULL
)

mybatis项目目录的大致结构为:

+---src
|   +---main
|   |   +---java
|   |   |   |   Test.java
|   |   |   |
|   |   |   +---pojo
|   |   |   |       Student.java
|   |   |   |
|   |   |   \---dao
|   |   |           IStudentDao.java
|   |   |
|   |   \---resources
|   |       |   log4j.properties
|   |       |   mybatis-config.xml
|   |       |
|   |       \---mappers
|   |               StudentMapper.xml

Test.java

import dao.IStudentDao;
import pojo.Student;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {
    public static void main(String args[]) throws Exception{
        String resource ="mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IStudentDao studentDAO = sqlSession.getMapper(IStudentDao.class);        
        Student currentStudent;
        
        currentStudent = studentDAO.getStudentById(1);        
        System.out.println(currentStudent);
        
        Thread.sleep(1000 * 30);
        
        currentStudent = studentDAO.getStudentById(1);        
        System.out.println(currentStudent);
    }
}

Student.java

package pojo;

public class Student {
    private int id;
    private String name;
    private int grade;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getGrade() {
        return this.grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    @Override
    public String toString(){
        return
                "id = " + id  + "\t" + "name = " + name  + "\t" + "grade = " + grade  + "\t";
    }
}

IStudentDao

package dao;

import org.apache.ibatis.annotations.Param;
import pojo.Student;


public interface IStudentDao {  
    public Student getStudentById(@Param("studentId") int studentId);
}

mybatis-config.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true"/>
        <property name="username" value="root"/>
        <property name="password" value="nihaonihao123123"/>
    </properties>
    
    <environments default="test">
        <environment id="test">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mappers/StudentMapper.xml"></mapper>
    </mappers>
</configuration>

StudentMapper.xml

<?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="dao.IStudentDao">
    <select id="getStudentById" resultType="pojo.Student">
        SELECT id AS id, name AS name, grade AS grade
        FROM student
        WHERE id = #{studentId} ;
    </select>
</mapper>

问题复盘

在第一次查询后,主线程暂停30秒,此时在MySQL WorkBench中修改了原来的数据,将“张三”变成“张三123”,主线程恢复后数据并没有任何变化。

开始以为是缓存问题,遂在mybatis-config.xml中禁用一级缓存:在configuration标签中,在 properties标签之后加入

<settings>
    <setting name="localCacheScope" value="STATEMENT"/>
</settings>

问题依旧(注意看时间的变化,确实进行了更新,查询的数据确实没有变化)

16:03:43    UPDATE test.student SET name = '张三123' WHERE id = 1 1 row(s) affected Rows matched: 1  Changed: 1  Warnings: 0  0.062 sec

MyBatis 查询结果-错误

开启mysql的查询日志比较差别

mysql> set GOLBAL general_log=on;
mysql> show variables like %general%;

mybatis提交事务-未提交

Mysql WorkBench 自动提交事务

注意:在我们的MyBatis中autocommit被设置为0,MySQL WorkBench中autocommit被设置为1

此时重新还原数据库数据,在Test.java手工加入提交

currentStudent = studentDAO.getStudentById(1);    
sqlSession.commit();    
System.out.println(currentStudent);

依然无效!!!

回顾一下,自动提交的问题确实存在,思路并没有问题。因此查询mybatis文档。

MyBatis 提交事务api

需要加入强制提交参数 true

currentStudent = studentDAO.getStudentById(1);    
sqlSession.commit(true);    
System.out.println(currentStudent);

加入后得到正确结果\::D

MyBatis 查询 正确结果

总结

在MySQL中,查询也是一次事务,如果没有提交,则每次查询的结果都是相同的。然而建议的还是关闭自动提交(autocommit=0,但MySQL还是会自动开启一个事务,只是不提交),这样在向多个表中写数据时可以保证一致性;对于增删改操作而言,(在单个客户端中)可以在确认执行后的数据正确,再提交,相当于提前模拟一遍。

猜你喜欢

转载自www.cnblogs.com/battor/p/mybatis_autocommit_problem.html