说明
当MybatisPlus自带的方法不满足我们使用时,我们需要新增全局的通用方法。
实现
主要分为以下三个步骤:
- 新建一个Mapper类来调用,
- 然后新建一个方法处理器处理新建的公共方法,
- 最后重建SQL注入器,
自定义Mapper
新建一个Mapper继承BaserMapper
1 2 3 4 5 6 7 8 9 10
| public interface AdviceMapper<T> extends BaseMapper<T> {
int insertOrUpdateBatch(@Param("list") List<T> entityList); }
|
自定义方法
新建一个方法继承AbstractMethod,并重写injectMappedStatement方法,构造出xml文件中类似的mybatis语法,然后添加到MappedStatement中
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class SaveOrUpdateBatchMethod extends AbstractMethod {
@Override public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return addInsertMappedStatement(mapperClass,modelClass,"insertOrUpdateBatch",sqlSource,new NoKeyGenerator(),null,null);
} }
|
自定义注入器
自定义注入器把刚构造的方法添加进去,一般继承DefaultSqlInjector
,就可以保留原来的已经有的方法
需要注意的是原来的方法需要保留的话需要调用super.getMethodList()
,即把原来DefaultSqlInjector
中的加载
AdviceSqlInjector 需要添加到容器中,MybatisPlus才能识别到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
@Component public class AdviceSqlInjector extends DefaultSqlInjector {
@Override public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) { List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo); methodList.add(new SaveOrUpdateBatchMethod()); return methodList; } }
|
修改业务的Mapper继承关系
默认的Mapper是继承BaseMapper的,要修改为自定义的mapper,如
1 2 3 4
| @Mapper public interface MeetingRoomMpMapper extends AdviceMapper<MeetingRoom> {
}
|