一.逻辑删除
一般在生产环境中都是采用逻辑删除,不会去物理删除数据,实现方式在我上一篇文章有说明。链接:mybatis-plus如何逻辑删除以及逻辑删除时如何实现填充公共字段-CSDN博客
二.物理删除
许多朋友说那我就想直接物理删除怎么办,这时候我们可以采用不调框架的方法,直接去手动写sql去实现。
其实我们还有另一种方式就是自定义一个方法实现物理删除。写一个公共的MyBaseMapper去继承BaseMapper,然后定义一个deleteAbsoluteById()方法。后面各个业务的mapper可以通过继承MyBaseMapper来使用。
public interface MyBaseMapper<T> extends BaseMapper<T> {
/**
* 物理删除
*
* @param id
* @return
*/
int deleteAbsoluteById(Serializable id);
}
光定义一个方法还不行,还要实现逻辑,我们需要建一个类去继承AbstractMethod,在这个类中实现相关逻辑。
public class DeleteAbsoluteById extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String method = "deleteAbsoluteById";
SqlMethod sqlMethod = SqlMethod.DELETE_BY_ID;
String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(), tableInfo.getKeyProperty());
SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, Object.class);
return this.addDeleteMappedStatement(mapperClass, method, sqlSource);
}
}
再自定义一个sql注入器继承DefaultSqlInjector,把deleteAbsoluteById()方法加入进去就大功告成。
public class CustomSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new DeleteAbsoluteById());
return methodList;
}
}
三.批量物理删除
批量物理删除同理,直接上代码。
public interface MyBaseMapper<T> extends BaseMapper<T> {
/**
* 物理删除
*
* @param id
* @return
*/
int deleteAbsoluteById(Serializable id);
/**
* 批量物理删除
*
* @param idList
* @return
*/
int deleteAbsoluteByIds(@Param(Constants.COLL) Collection<?> idList);
}
public class DeleteAbsoluteByIds extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String method = "deleteAbsoluteByIds";
SqlMethod sqlMethod = SqlMethod.DELETE_BATCH_BY_IDS;
String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(), SqlScriptUtils.convertForeach(SqlScriptUtils.convertChoose("@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(item.getClass())", "#{item}", "#{item." + tableInfo.getKeyProperty() + "}"), "coll", (String) null, "item", ","));
SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, Object.class);
return this.addDeleteMappedStatement(mapperClass, method, sqlSource);
}
}
public class CustomSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new DeleteAbsoluteById());
methodList.add(new DeleteAbsoluteByIds());
return methodList;
}
}
到此为止我们就实现了物理删除和批量物理删除。
四.总结
如有错误之处,欢迎指正。如有疑问,欢迎讨论。