我们已经知道,在MP中,通过AbstractSqlInjector将BaseMapper中的方法注入到了Mybatis容器,这样这些方法才可以正常执⾏。
那么,如果我们需要扩充BaseMapper中的⽅法,⼜该如何实现呢?
下⾯我们以扩展findAll⽅法为例进行学习。
1、编写MyBaseMapperpublic interface MyBaseMapperextends BaseMapper { public List findAll(); }
其他的Mapper都可以继承该Mapper,这样实现了统⼀的扩展。
如:
public interface UserMapper extends MyBaseMapper{ public User findById(Long id); }
2、编写MySqlInjector
如果直接继承AbstractSqlInjector的话,原有的BaseMapper中的⽅法将失效,所以我们选择继承DefaultSqlInjector进行扩展。
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List getMethodList() {
List methodList = super.getMethodList();
// 扩充自定义方法
methodList.add(new FindAll());
return methodList;
}
}
3、编写FindAll
public class FindAll extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class> mapperClass, Class> modelClass, TableInfo tableInfo) {
String sql = "select * from " + tableInfo.getTableName();
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addSelectMappedStatement(mapperClass, "findAll", sqlSource, modelClass, tableInfo);
}
}
4、注册到Spring容器
@Bean
public MySqlInjector mySqlInjector(){
return new MySqlInjector();
}
5、测试
@Test
public void testFindAll(){
List users = this.userMapper.findAll();
for (User user : users) {
System.out.println(user);
}
}
输出的SQL:
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] ==> Preparing: select
* from tb_user
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] ==> Parameters:
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] <== Total: 10
⾄此,我们实现了全局扩展SQL注⼊器。



