mybatis 更新时为什么返回值是-1
原因
返回-1,是由于defaultExecutorType的引起的,defaultExecutorType有三个执行器SIMPLE、REUSE和BATCH。
默认情况下,mybatis 的 update 操作返回值是记录的 matched 的条数,并不是影响的记录条数。将 MyBatis 中的 executorType 修改成 BATCH 【批量模式】后,会让更新结果 返回值变成 -1
解决
在 Spring 配置文件中,做如下修改
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
// BATCH 改为 SIMPLE
其中BATCH可以批量更新操作缓存SQL以提高性能,但是有个缺陷就是无法获取update、delete返回的行数
分析
默认情况下,mybatis 的 update 操作返回值是记录的 matched 的条数,并不是影响的记录条数。
mybatis 仅仅只是返回的数据库连接驱动(通常是 JDBC )的返回值,也就是说,驱动告知更新 2 条记录受影响。
通过对 JDBC URL 显式的指定 useAffectedRows 选项,我们将可以得到受影响的记录的条数:
jdbc:mysql://${jdbc.host}/${jdbc.db}?useAffectedRows=true
MyBatis 插入模式:ExecutorType
Mybatis 内置的 ExecutorType 有3种
- simple [默认],
- batch
- Reuse
SimpleExecutor - 该模式下每执行一次update或select,就开启一个Statement对象,用完立刻关闭Statement对象。(可以是Statement或PrepareStatement对象)
BatchExecutor - 执行update(没有select,JDBC批处理不支持select),将所有sql都添加到批处理中(addBatch()),等待统一执行(executeBatch())