前言 mybatisplus 的好处就不用多说了,带给我们最大的好处就是不用再重复编写那些简单的sql语句。但是多表查询的时候却还是不得不用xml来解决,但是想要偷懒,不想写xml,于是去网上搜索了下是否有连表插件,居然还真有。于是乎就拿下来试用下,问题就来了,由于项目里有写过自定义的sql注入器,加上链表插件后,启动居然报错了,于是乎查看源码分析原因,发现连表插件里也用到了sql注入器,原来如此,现在问题显而易见了。
解决办法 因为连表插件里和项目原先配置里都有sql注入器,导致springboot容器在实例化类时不知选择哪一个,所以报错Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed。
看错误原因就知道该如何解决了,在项目原有的sql注入器实现类上加上@Primary 注解,意思是默认优先选择:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor paginationInterceptor () { interceptor.addInnerInterceptor(new MPJInterceptor ()); return interceptor; } @Bean @Primary public MySqlInjector myLogicSqlInjector () { return new MySqlInjector (); } }
这样虽然解决了报错问题,但是新的问题又出现了,由于设置了@Primary 默认加载,意味着连表插件里的功能就没法加载进去了,所以需要手动把里面实现的方法重新加入到项目里原有的sql注入器里:
先查看连表插件的源码,找到sql注入器的加载类,如下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.github.yulichang.injector;import com.baomidou.mybatisplus.core.injector.AbstractMethod;import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;import com.github.yulichang.method.*;import java.util.List;public class MPJSqlInjector extends DefaultSqlInjector { @Override public List<AbstractMethod> getMethodList (Class<?> mapperClass) { List<AbstractMethod> list = super .getMethodList(mapperClass); list.add(new SelectJoinOne ()); list.add(new SelectJoinList ()); list.add(new SelectJoinPage ()); list.add(new SelectJoinMap ()); list.add(new SelectJoinMaps ()); list.add(new SelectJoinMapsPage ()); return list; } }
将注入器里添加的方法添加到项目原有的sql注入器里,如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import java.util.List;import com.baomidou.mybatisplus.core.injector.AbstractMethod;import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;import com.github.yulichang.method.SelectJoinList;import com.github.yulichang.method.SelectJoinMap;import com.github.yulichang.method.SelectJoinMaps;import com.github.yulichang.method.SelectJoinMapsPage;import com.github.yulichang.method.SelectJoinOne;import com.github.yulichang.method.SelectJoinPage;public class MySqlInjector extends DefaultSqlInjector { @Override public List<AbstractMethod> getMethodList (Class<?> mapperClass) { List<AbstractMethod> methodList = super .getMethodList(mapperClass); methodList.add(new MysqlInsertOrUpdateBatch ()); methodList.add(new InsertBatchSomeColumn (t->true )); methodList.add(new MysqlUpdateBatch ()); methodList.add(new SelectJoinOne ()); methodList.add(new SelectJoinList ()); methodList.add(new SelectJoinPage ()); methodList.add(new SelectJoinMap ()); methodList.add(new SelectJoinMaps ()); methodList.add(new SelectJoinMapsPage ()); return methodList; } }
最后保存代码,完美启动,测试功能正常,OK