
mybatis批量插入数据时拦截器失效
问题描述:在项目中使用mybatis编写了拦截器,为插入或更新的数据自动填充基础字段值。但在使用批量插入数据的方法时,拦截器却失效,导致基础字段无法赋值。
代码示例:
@component
@intercepts({
@signature(type = executor.class,method = "update",args = {mappedstatement.class, object.class})
})
public class mybatisautofillplugin implements interceptor {
// ...
}这个问题的根源在于批量插入语句使用的是foreach标签,该标签会将一个集合中的元素逐一插入到数据库中。此时拦截器只拦截了executor.update方法,无法拦截批量插入的执行过程。因此需要额外拦截statementhandler.update方法来解决此问题。
解决方法:
@Intercepts({
@Signature(type = Executor.class,method = "update",args = {MappedStatement.class, Object.class}),
@Signature(type = StatementHandler.class,method = "update",args = {Statement.class})
})
public class MyBatisAutoFillPlugin implements Interceptor {
// ...
}添加拦截statementhandler.update方法后,拦截器即可正常工作,为批量插入的数据正确填充基础字段值。










