Mybatis執行update失敗
今天在進行分布式重構項目的時候碰到一個問題,在執行sql的時候只有update不能成功,其他語句都可以正常執行,報錯如下: 版本:org.mybatis:mybatis:3.4.5
接口
1
2
|
@UpdateProvider (type = ManagerProvider. class , method = "updateManager" ) int updateManager(Manager manager) throws Exception; |
報錯信息
Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
org.springframework.jdbc.UncategorizedSQLException: Error getting generated key or setting result to parameter object. Cause: java.sql.SQLException: 不允許的操作;uncategorized SQLException for SQL []; SQL state [99999]; error code [17090]; 不允許的操作; nested exception is java.sql.SQLException: 不允許的操作
原因
由于mybatis在執行insert和update的時候都默認生成key,然后注入,所以在執行update的時候會報錯。
解決辦法
在接口上增加注解 @Options(useGeneratedKeys = false),不讓mybatis自動注入key,問題解決。
1
2
3
|
@UpdateProvider (type = ManagerProvider. class , method = "updateManager" ) @Options () // @Options(useGeneratedKeys = false) int updateManager(Manager manager) throws Exception; |
最后說明一點,版本:org.mybatis:mybatis:3.4.4這個版本沒有此類問題。
Mybatis插入(更新)失敗 卻不報錯
問題描述
mybatis進行數據插入或更新操作,方法成功執行,數據庫中卻不存在新數據,原本代碼如下:
1
2
3
4
5
6
7
8
9
|
@Test public void test7() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); EmployeeMapperDynamicSql mapper = sqlSession.getMapper(EmployeeMapperDynamicSql. class ); mapper.addEmps(Collections.singletonList(employee)); sqlSession.close(); } |
解決方案
在插入或更新語句后,增添commit,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
@Test public void test7() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); EmployeeMapperDynamicSql mapper = sqlSession.getMapper(EmployeeMapperDynamicSql. class ); mapper.addEmps(Collections.singletonList(employee)); /*添加commit*/ sqlSession.commit(); sqlSession.close(); } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/wgxaszc8/article/details/79276267