一个Mybatis学习中遇到SelectKey返回值始终为1的问题
最近在跟着某视频教程学MyBatis,视频中用到了@SelectKey 这个注解,作用是返回自增的主键
@SelectKey(keyColumn="id",keyProperty="id",resultType=long.class,before=false,statement="select last_insert_id()") public long insert(OrderInfo orderInfo);
调用的代码如下
long orderId = orderDao.insert(orderInfo);
其中获取的返回值orderID始终为1,然而视频作者并没有发现这个问题,通过梳理程序逻辑,确认逻辑没错,应该返回的ID数据库的自增ID
于是翻查了官方文档 http://www.mybatis.org/mybatis-3/zh/java-api.html#sqlSessions
根据官方文档的解释,这个keyProperty的意思其实就是传进来的Domain对象的对应属性,例如我这里的例子就是OrderInfo对象中名为id的属性
所以问题是在这里,所以正确的用法应该是从orderInfo中去取keyProperty定义的属性的值,例如我这里的是id,那就是这个id属性:
orderDao.insert(orderInfo); long orderId = orderInfo.getId() ;
那返回值1又是什么意思?这里通过调试来看:
以我现在这个代码为例,当我调用orderDao.insert(orderInfo);方法的时候,MyBatis通过动态代理机制,调用了:
org.apache.ibatis.binding.MapperProxy.invoke(Object, Method, Object[])
这个方法的源码为:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else if (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); }
根据代码逻辑,我的method.getDeclaringClass()是一个Interface的DAO,所以最终执行的是最后的org.apache.ibatis.binding.MapperMethod.execute(SqlSession, Object[])
这个方法的代码如下:
public Object execute(SqlSession sqlSession, Object[] args) { Object result; switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args); } else { Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; }
从上面的代码上看,最终return的返回时其实是rowCountResult,也就是这条sql最终影响的行数
为了验证这个问题,写一个测试用例:
userDao.insertTest(OrderInfo orderInfo)方法如下,其中insert语句一次性插入了3行数据,返回值存入到orderInfo的id属性中:
@Insert("INSERT INTO test(b,c) VALUES(1,1),(2,2),(3,3)") @SelectKey(keyColumn="id",keyProperty="id",resultType=long.class,before=false,statement="select last_insert_id()") public long insertTest(OrderInfo orderInfo);
同时我们取出orderDao.insertTest的返回值:
long ret = orderDao.insertTest(orderInfo); System.out.println("=====>\nret:"+ret);
同时为了让结果更加直观,我把test表的自增量设置为从4开始,a为自增字段
最终测试结果如下,返回值为3,最终自增ID为7,验证了之前的猜想,直接从dao的方法中取出来的只是操作的行数,最终的自增ID应该是通过你传入的对象,并且在keyProperty定义的属性名中取出来。