AutoSqlInjector
BaseMapper提供了17个常用的方法,但是有些需求可能无法很好的实现,MP提供了自定义全局操作来解决这个问题。
mapper接口中定义方法
public interface EmployeeMapper extends BaseMapper<Employee> {
// 1.在Mapper接口中定义相关的CRUD方法
// 2.扩展AutoSqlInjector inject方法,实现Mapper接口中方法要注入的SQL
// 3.在MP的全局策略中,配置自定义注入器
//希望这个方法启动过的时候自动注入
//之前需要在xml中进行配置的SQL语句,现在通过AutoSqlInjector在加载mybatis环境时就注入
int deleteItemById(int id);
}
编写自定义的注入类
public class MyInjector extends AutoSqlInjector {
/**
* 扩展inject方法
*/
@Override
public void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class<?> mapperClass,
Class<?> modelClass, TableInfo table) {
System.out.println("自定义injector执行,mapperClass = " + mapperClass.getName());
//将EmployeeMapper中定义的deleteAll,处理成对应的MappedStatement对象,加入到configuration对象中。
String sql="delete from " + table.getTableName() + " where id=#{id}";
//要注入的方法名 一定要与EmployeeMapper接口中的方法名一致
String method="deleteItemById";
//构造sqlSource对象
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addDeleteMappedStatement(mapperClass, method, sqlSource);
}
}
配置文件中进行配置
<!-- 定义自定义注入器 -->
<bean id="myInjector" class="com.ezerbel.mp.injector.MyInjector"></bean>
<bean id="mpGlobalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!-- 表名、字段名、是否使用下划线命名(默认 true: 数据库下划线命名) -->
<property name="dbColumnUnderline" value="true"></property>
<!-- 全局的主键策略 -->
<property name="idType" value="0"></property>
<!-- 全局的表前缀配置 -->
<property name="tablePrefix" value="tb_"></property>
<!-- 注入自定义的全局操作 -->
<property name="sqlInjector" ref="myInjector" ></property>
</bean>
测试
public class TestInjector {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeMapper employeeMapper = ctx.getBean("employeeMapper", EmployeeMapper.class);
UserMapper userMapper = ctx.getBean("userMapper",UserMapper.class);
@Test
public void testMySqlInjector1() {
employeeMapper.deleteItemById(1);
}
}