zl程序教程

您现在的位置是:首页 >  其他

当前栏目

MyBaitsPlus---Sql 注入器知识点补充

2023-03-14 22:34:01 时间

自定义全局操作知识点补充


Sql 注入器

概念

就是让你自己写的sql语句和mp的默认sql语句(basemapper中的sql语句)一起启动,就不需要写映射文件了

根据MybatisPlus 的AutoSqlInjector可以自定义各种你想要的sql ,注入到全局中,相当于自定义Mybatisplus 自动注入的方法。

之前需要在xml中进行配置的SQL语句,现在通过扩展AutoSqlInjector 在加载mybatis环境时就注入。


步骤

1.定义SQL(继承AbstractMethod 子类)

public class FullAll extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass,
                                                 TableInfo tableInfo) {
        String sqlMethod = "findAll";
        String sql = "select * from " + tableInfo.getTableName();
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addSelectMappedStatementForTable(mapperClass, sqlMethod, sqlSource, tableInfo);
    }
}

2.注册(SQL 注入)

public class SqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
      methodList.add(new FullAll());
        return methodList;
    }
}

3.对象配置(放入到容器中)

    @Bean
    public SqlInjector sqlInjector() {
        return new SqlInjector();
    }

4.把方法定义到BaseMapper(继承 BaseMapper 进行扩展,添加扩展的方法)

public interface BaseMapperPlus<T> extends BaseMapper<T> {
    List<T> findAll();
}

5.继承 BaseMapperPlus

@Mapper
public interface UserMapper extends BaseMapperPlus<User>
{
}

6.测试

@SpringBootTest
class SpringBootDaoApplicationTests
{
    @Autowired
    UserMapper userMapper;

    @Test
    void test6() {
        List<User> all = userMapper.findAll();
        all.forEach(System.out::println);
    }
}

注意

public interface MyBaseMapper<T> extends BaseMapper<T> {
    int mysqlInsertAllBatch(@Param("list") List<T> batchList);
}

演示批量保存使用mysql特有语法:

insert into user(id, name, age) values (1, "a", 17), (2,"b", 18)

坑点:

  • 在演示自定义批量和自动填充功能时,需要在mapper方法的参数上定义@Param(),
  • 而mp默认仅支持 list, collection, array 3个命名,不然无法自动填充