MybatisPlus的sql注入器使用!



本文代碼樣例均已上傳至Gitee: https://gitee.com/tqbx/springboot-samples-learn

基本使用

  1. 創建方法的類,繼承AbstractMethod。
/**
 *
 * 刪除全部
 * @author Summerday
 */
public class DeleteAll extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        // 執行sql,動態sql參考類SqlMethod
        String sql = "delete from " + tableInfo.getTableName();
        // mapper方法接口名一致
        String method = "deleteAll";

        SqlSource sqlSource = 
            languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addDeleteMappedStatement(mapperClass,method,sqlSource);
    }
}
  1. 創建注入器,既可以繼承DefaultSqlInjector,也可以實現ISqlInjector接口。
/**
 * 自定義sql注入
 * @author Summerday
 */
@Component
public class MySqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {

        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        //增加自定義方法
        methodList.add(new DeleteAll());
        methodList.add(new FindOne());

        /*
         * 以下 3 個為內置選裝件
         * 頭 2 個支持字段篩選函數
         */
        // 例: 不要指定了 update 填充的字段
        methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
        methodList.add(new AlwaysUpdateSomeColumnById());
        methodList.add(new LogicDeleteByIdWithFill());
        return methodList;
    }
}
  1. 如果想要所有的mapper都擁有自定義的方法,可以自定義接口繼承BaseMapper接口,我們的業務接口就可以繼承自定義的baseMapper接口了。
/**
 * 自定義baseMapper接口
 * @author Summerday
 */
public interface MyBaseMapper<T> extends BaseMapper<T> {

    //自定義方法,刪除所有,返回影響行數
    int deleteAll();

    // 根據id找到
    T findOne(Serializable id);
}

@Mapper
public interface UserMapper extends MyBaseMapper<User> {
}
  1. 測試接口
@RunWith(SpringRunner.class)
@SpringBootTest
class InjectTest {

    @Resource
    UserMapper userMapper;

    @Test
    void inject(){
        int rows = userMapper.deleteAll();
        System.out.println(rows);
    }

    @Test
    void findOne(){
        User one = userMapper.findOne(1L);
        System.out.println(one);
    }
}

選裝件

  1. InsertBatchSomeColumn:批量新增數據,自選字段insert

  2. LogicDeleteByIdWithFill:根據id邏輯刪除數據,並帶字段填充功能

  3. AlwaysUpdateSomeColumnById:根據 ID 更新固定的那幾個字段(但是不包含邏輯刪除)

        /*
         * 以下 3 個為內置選裝件
         * 頭 2 個支持字段篩選函數
         */
        // 例: 不要指定了 update 填充的字段  排除邏輯刪除,和"age"字段
        methodList.add(new InsertBatchSomeColumn(
            i -> i.getFieldFill() != FieldFill.UPDATE 
            && !i.isLogicDelete() 
            && !"age".equals(i.getColumn())));
        // 篩選字段
        methodList.add(new AlwaysUpdateSomeColumnById(
            i -> !"age".equals(i.getColumn())));
        methodList.add(new LogicDeleteByIdWithFill());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM