背景:通過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);