背景:通过Mybatis插入数据或更新数据,显示插入/更新成功,查询数据库,发现并未插入成功、数据也没更新成功。下面是Mapper文件
public interface TestOrmMapper {int insertByTest(@Param("requestId") Integer requestId, @Param("dataType") Integer dataType,@Param("roleKey") String roleKey, @Param("roleNameCn") String roleNameCn, @Param("roleNameEn") String roleNameEn);int updateById(@Param("id") Integer id, @Param("roleKey") String roleKey, @Param("roleNameCn") String roleNameCn, @Param("roleNameEn") String roleNameEn);
}
<?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="com.ecology.mapper.TestOrmMapper"><insert id="insertByTest">insert into plm_role_project_bak(requestId, data_type, role_key, role_name_cn, role_name_en)values(#{requestId}, #{dataType}, #{roleKey}, #{roleNameCn}, #{roleNameEn})</insert><update id="updateById">update plm_role_project_bak set role_key = #{roleKey}, role_name_cn = #{roleNameCn}, role_name_en = #{roleNameEn} where id = #{id}</update>
</mapper>
调用代码块:
Integer requestId = 2938939;
TestOrmMapper testMapper = sqlSession.getMapper(TestOrmMapper.class);
int test = testMapper.insertByTest(requestId, 11, "role_01", "角色中文名", "role_name");
LOGGER.info("======>>>Insert请求结果test:{}", test);String roleKey = "role_02";
String roleName = "角色中文名";
String roleEnName = "role_code";
int id = testMapper.updateById(1, roleKey, roleEnName, roleName);
LOGGER.info("======>>>Update请求结果id:{}", id);
控制台执行的日志:
通过日志可看insert、update返回都是执行成功;但是数据库中的数据还是没有任何修改
本地调试一下,可以通过日志看到原因:插入的语句回滚连接数据库了,导致插入失败。
这种情况下,我们可以使用 sqlSession.commit()手动执行提交事件,将数据提交到数据库中
//手动执行提交事件,将数据提交到数据库中,才真正成功插入到数据库中
sqlSession.commit();
或者我们在使用sqlSessionFactory.openSession()时候,将openSession( )的值设为 true 自动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
看DefaultSqlSessionFactory源码,可以看到提供了两个openSession方法
使用无参的方法时,需要配合commit使用,不然不会提交,导致数据操作回滚而失败
解决方式:
- 将 openSession( )的值设为 true
SqlSession sqlSession = sqlSessionFactory.openSession(true);
- 配合commit使用
SqlSession sqlSession = sqlSessionFactory.openSession();Integer requestId = 2938939;
TestOrmMapper testMapper = sqlSession.getMapper(TestOrmMapper.class);
int test = testMapper.insertByTest(requestId, 11, "role_01", "角色中文名", "role_name");
sqlSession.commit();//手动执行提交事件,将数据提交到数据库中,才真正成功插入到数据库中
LOGGER.info("======>>>Insert请求结果test:{}", test);String roleKey = "role_02";
String roleName = "角色中文名";
String roleEnName = "role_code";
int id = testMapper.updateById(1, roleKey, roleEnName, roleName);
sqlSession.commit();//手动执行提交事件,将数据提交到数据库中,才真正成功插入到数据库中
LOGGER.info("======>>>Update请求结果id:{}", id);