一、首先在Mapper接口中定义好你需要自定义的方法 ,返回值记得用Integer代替int类型
public interface EmployeeMapper extends BaseMapper<Employee> {
Integer deleteById(Integer id);
}
二、在工具类中新建一个class类,命名为 LogicSqlInjector,然后继承AbstractSqlInjector类,并且实现其方法,并把上面定义的方法加进去,如下:
public class LogicSqlInjector extends AbstractSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
List<AbstractMethod> list = new ArrayList<>();
//获取父类的所有方法
list.addAll(super.getMethodList());
//将自己的方法注入进去
list.add(new deleteById());
return list;
}
}
三、在工具类中新建一个class类,命名为刚才的方法名,deleteById,继承AbstractLogicMethod类,并实现其方法,如下
public class deleteById extends AbstractLogicMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass,
Class<?> modelClass, TableInfo tableInfo) {
String sql = "DELETE FROM "+ tableInfo.getTableName()+" where id = #{id} " ;
String method = "deleteById";
SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
return this.addSelectMappedStatement(mapperClass,method, sqlSource, Map.class, tableInfo);
}
}
备注:可以参考第二点中其他Logic方法的实现过程,在这个自定义类中可以直接套用其他方法的模板。
此代码块中的String sql为自己定义的sql语句, String method为定义的方法名,其他都是父类中自带的参数,只要把sql和method写进来就行了。
tableInfo中含有当前操作表的任何信息,这是mp对于数据库字段的映射,比如在employee表中操作,此时tableInfo.getTableName()获取到的值就是employee,具体的源码可以按住ctrl点进去看。
四、去ApplicationContext.xml配置文件中,将自定义的类注入进全局变量
<!-- ****************** 定义mybatisplus全局配置 ****************** -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<!-- 注入自定义全局sql注入操作 -->
<property name="sqlInjector" ref="logicSqlInjector"/>
</bean>
<!--自定义注入器-->
<bean id="logicSqlInjector" class="com.atguigu.mp.utils.mybatisplus.injector.LogicSqlInjector"/>
class的路径是刚才在工程下创建的LogicSqlInjector的地址
五、将mybatisplus全局配置注入进sqlSessionFactory
<!-- ****************** 定义mybatisplus全局配置 ****************** -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<!-- 注入自定义全局sql注入操作 -->
<property name="sqlInjector" ref="logicSqlInjector"/>
</bean>
<!-- ****************** 需要放进全局配置中的组件 ****************** -->
<!--自定义注入器-->
<bean id="logicSqlInjector" class="com.atguigu.mp.utils.mybatisplus.injector.LogicSqlInjector"/>
六、测试
@Test
public void testdelall(){
Integer result = employeeMapper.deleteById(3);
System.out.println("result = " + result);
}
七、结果
这只是快速上手的方法,具体源码小伙伴们自己看
或者参考这位大神的文章https://www.cnblogs.com/liuyangfirst/p/9744011.html