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方法后,攔截器即可正常工作,為批量插入的數據正確填充基礎字段值。