记录 MyBatis Plus 在多数据源场景下 saveBatch 调用失败的问题表现、原因与解决思路。
问题现象
仅配置单个数据源时,MyBatis Plus 的 save / saveBatch 接口都能正常调用;但在多数据源、动态切换的场景下,save 正常而 saveBatch 调用失败,报错如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
org.apache.ibatis.exceptions.PersistenceException: ### Error flushing statements. Cause: org.apache.ibatis.executor.BatchExecutorException: com.xxx.survey.mapper.SurveyAnswerMapper.insert (batch index #1) failed. Cause: java.sql.BatchUpdateException: 对象名 't_survey_answer' 无效。 ### Cause: org.apache.ibatis.executor.BatchExecutorException: com.xxx.survey.mapper.SurveyAnswerMapper.insert (batch index #1) failed. Cause: java.sql.BatchUpdateException: 对象名 't_survey_answer' 无效。 at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.flushStatements(DefaultSqlSession.java:255) at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.saveBatch(ServiceImpl.java:128) at com.baomidou.mybatisplus.extension.service.IService.saveBatch(IService.java:58) at com.baomidou.mybatisplus.extension.service.IService$$FastClassBySpringCGLIB$$f8525d18.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671) at com.xxx.survey.service.impl.SurveyAnswerServiceImpl$$EnhancerBySpringCGLIB$$dbeefaf3.saveBatch(<generated>) at com.xxx.survey.ServiceTest.testGetAttendanceRecord(ServiceTest.java:91) at sun.refl