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个命名,不然无法自动填充
相关文章
- 在 Go 里用 CGO?这 7 个问题你要关注!
- 9款优秀的去中心化通讯软件 Matrix 的客户端
- 求职数据分析,项目经验该怎么写
- 在OKR中,我看到了数据驱动业务的未来
- 火山引擎云原生大数据在金融行业的实践
- OpenHarmony富设备移植指南(二)—从postmarketOS获取移植资源
- 《数据成熟度指数》报告:64%的企业领袖认为大多数员工“不懂数据”
- OpenHarmony 小型系统兼容性测试指南
- 肯睿中国(Cloudera):2023年企业数字战略三大趋势预测
- 适用于 Linux 的十大命令行游戏
- GNOME 截图工具的新旧截图方式
- System76 即将推出的 COSMIC 桌面正在酝酿大变化
- 2GB 内存 8GB 存储即可流畅运行,Windows 11 极致精简版系统 Tiny11 发布
- 迎接 ecode:一个即将推出的具有全新图形用户界面框架的现代、轻量级代码编辑器
- loongarch架构介绍(三)—地址翻译
- Go 语言怎么解决编译器错误“err is shadowed during return”?
- 敏捷:可能被开发人员遗忘的部分
- Denodo预测2023年数据管理和分析的未来
- 利用数据推动可持续发展
- 在 Vue3 中实现 React 原生 Hooks(useState、useEffect),深入理解 React Hooks 的