- 在MyBatis-Plus中通过AbstractSqlInjector将BaseMapper中的方法注入到MyBatis容器,这样这些方法才可以正常执行
如何扩展BaseMapper中的方法-
文件结构
-
编写MyBaseMapper
- 泛型设置为缺损的值,传入什么类型的对象就填入什么对象
public interface MyBaseMapper<T> extends BaseMapper<T> {
public List<T> findAll();
}
编写FindAll方法类
- 继承AbstractMethod类,实现它的方法
- 参考selectById来实现
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);
}
}
MySqlInjector类
- 如果继承的是
AbstractSqlInjector会导致plus插件内置的BaseMapper中的方法不能使用 - 继承
DefaultSqlInjector并且将父类中的方法集合添加进入到list中去就可以扩展自己写的方法 -
类的继承关系
-
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
List<AbstractMethod> list = new ArrayList<>();
list.addAll(super.getMethodList());
list.add(new FindALL());
return list;
}
}
MySqlInjector注入到Spring的容器中
@Bean
public MySqlInjector mySqlInjector(){
return new MySqlInjector();
}
测试
@Test
public void testFindALl(){
List<User> users = this.userMapper.findAll();
users.forEach(user -> System.out.println(user));
}
Execute SQL:
select
*
from
tb_user