SpringBoot整合Mybatis自定义 * 不起作用的处理方案
作者:小胖学编程 发布时间:2023-03-19 04:35:14
SpringBoot整合Mybatis自定义 * 不起作用
Mybatis插件生效的方式:
1. 原始的读取mybatis-config.xml文件
该方式和Spring无关,是通过反射的形式创建插件对象,此时会执行org.apache.ibatis.plugin.Interceptor#setProperties方法,以读取配置参数。
mybatis:
mapper-locations: classpath*:/mapping/*.xml
type-aliases-package: com.tellme.pojo
#读取全局配置的地址
config-location: classpath:mybatis-config.xml
在resource目录下配置mybatis的全局配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer"/>
<typeAlias alias="Long" type="java.lang.Long"/>
<typeAlias alias="HashMap" type="java.util.HashMap"/>
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
<typeAlias alias="ArrayList" type="java.util.ArrayList"/>
<typeAlias alias="LinkedList" type="java.util.LinkedList"/>
</typeAliases>
<!--配置的插件名-->
<plugins>
<plugin interceptor="com.xxx.yyy.plugins.PrintSqlInfoInterceptor"/>
</plugins>
</configuration>
2. 与SpringBoot容器整合
网上很多方案说:mybatis自定义 * 上加上@Component注解便可以生效。但是我将自定义 * 放入到Spring容器中,自定义 * 却失效了。
然后找到了springboot配置多数据源后mybatis * 失效文章,说是自定义配置了数据源导致了 * 失效。
2.1 mybatis的自动装载
源码位置:org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
@Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {
private static Log log = LogFactory.getLog(MybatisAutoConfiguration.class);
@Autowired
private MybatisProperties properties;
//会依赖注入Spring容器中所有的mybatis的Interceptor *
@Autowired(required = false)
private Interceptor[] interceptors;
...
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
factory.setConfiguration(properties.getConfiguration());
//手动放入到了setPlugins方法中。
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
factory.setMapperLocations(this.properties.resolveMapperLocations());
}
return factory.getObject();
}
...
}
上面源码中:自动注入了Interceptor[]数组(我们只需将mybatis的自定义 * 对象放入到Spring容器中)。后续放入了sqlSessionFactory中。
但是项目中虽然自定义配置了sqlSessionFactory类,但却未设置factory.setPlugins(this.interceptors);。导致即使将自定义 * 放入到Spring容器,但却不生效。
解决方法,需要手动修改自定义的sqlSessionFactory类。
3. 在mybatis-config.xml配置又放入Spring容器
这种情况下,mybatis自定义 * 会被执行两次。即在mybatis-config.xml配置的 * 会通过反射的方式创建 * ,放入Spring容器的 * 也会被初始化。
源码位置:org.mybatis.spring.SqlSessionFactoryBean#buildSqlSessionFactory
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
...读取属性中的plugins,即org.mybatis.spring.SqlSessionFactoryBean#setPlugins设置的。
if (!isEmpty(this.plugins)) {
for (Interceptor plugin: this.plugins) {
configuration.addInterceptor(plugin);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Registered plugin: '" + plugin + "'");
}
}
}
...解析xml配置(通过反射创建 * 对象)
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'");
}
} catch(Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
最终会执行到:
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child: parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
//反射创建mybatis的插件。
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance);
}
}
}
SpringBoot 自定义Mybatis *
开发过程中经常回需要对要执行的sql加以自定义处理,比如分页,计数等。通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。
@Intercepts({@Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class, RowBounds.class,ResultHandler.class})})
public class MyPageInterceptor implements Interceptor {
private static final Logger logger= LoggerFactory.getLogger(MyPageInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
logger.warn(invocation.toString());
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o,this);
}
@Override
public void setProperties(Properties properties) {
logger.warn(properties.toString());
}
}
我的配置
mybatis:
type-aliases-package: me.zingon.pagehelper.model
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 100
default-statement-timeout: 30
在springboot中要给mybatis加上这个 * ,有三种方法,前两种方法在启动项目时不会自动调用自定义 * 的setProperties方法。
第一种
直接给自定义 * 添加一个@Component注解,当调用sql时结果如下,可以看到 * 生效了,但是启动时候并没有自动调用setProperties方法。
第二种
在配置类里添加 * ,这种方法结果同上,也不会自动调用setProperties方法。
@Configuration
public class MybatisConfig {
@Bean
ConfigurationCustomizer mybatisConfigurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.addInterceptor(new MyPageInterceptor());
}
};
}
}
第三种
这种方法就是跟以前的配置方法类似,在yml配置文件中指定mybatis的xml配置文件,注意config-location属性和configuration属性不能同时指定
mybatis:
config-location: classpath:mybatis.xml
type-aliases-package: me.zingon.pagehelper.model
mapper-locations: classpath:mapper/*.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="me.zingon.pacargle.model"/>
</typeAliases>
<plugins>
<plugin interceptor="me.zingon.pagehelper.interceptor.MyPageInterceptor">
<property name="dialect" value="oracle"/>
</plugin>
</plugins>
</configuration>
可以看到,在启动项目的时候setProperties被自动调用了
前两种方法可以在初始化自定义 * 的时候通过 @Value 注解直接初始化需要的参数。
来源:https://www.jianshu.com/p/5fddb7f67108
猜你喜欢
- 著名的Java单元测试框架Junit 4已经出来很长时间了,当时我发现JUnit 5已经处于测试版,就准备写文章来介绍JUnit 5.不过因
- java 中newInstance()方法和new关键字的区别* 它们的区别在于创建对象的方式不一样,前者是使用类加载机制,后者是创建一个新
- 什么是 MyBatis 缓存使⽤缓存可以减少 Java 应⽤与数据库的交互次数,从而提升程序的运行效率。⽐如查询出 id = 1 的对象,第
- 前言需要对一个List中的对象进行唯一值属性去重,属性求和,对象假设为BillsNums,有id、nums、sums三个属性,其中id表示唯
- 前言与消息发送紧密相关的几行代码:1. DefaultMQProducer producer = new DefaultMQProducer
- 项目运行:环境配置:Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,M
- [LeetCode] 2. Add Two Numbers 两个数字相加You are given two non-empty&n
- 什么是ShiroApache Shiro是一个功能强大且易于使用的Java安全框架,它执行身份验证、授权、加密和会话管理。借助Shiro易于
- 最近做了很多项目,不同的系统,不同的部署方式,这里做个记录1.在jar包目录新建一个start.bat 文件,然后写入启动命令j
- 前言不积跬步无以至千里,不积小流,无以成江海在公司一般来说,都只会接触一些CRUD的业务,很多时候可能你想设计很多的代码结构,但是时间不允许
- 0、线程的本质线程不是一个计算机硬件的功能,而是操作系统提供的一种逻辑功能,线程本质上是进程中一段并发运行的代码,所以线程需要操作系统投入C
- 微服务治理Spring Cloud 工具套件为微服务治理提供了全面的技术支持。这些治理工具主要包括服务的注册与发现、负载均衡管理、动态路由、
- 1.最常用的方法是创建一个计数器,判断是否遇到‘\0',不是'\0'指针就往后加一。int my_strlen(co
- 引言java中的Math.random()是一个在[0,1)范围等概率返回double数值类型的算法,基于此函数,我们来延申一些随机概率算法
- 前言最近被问到了这个问题,第一次回答的也是很不好,在此参考网上答案进行整理记录。供大家学习参考。Synchronized修饰非静态方法Syn
- 概述背景函数式编程的理论基础是阿隆佐·丘奇(Alonzo Church)于 1930 年代提出的 &lambd
- C#与Java相比较从整体上来看,c#和java及其相似,甚至超过了c#与c、c++的相似程度,下面是两种语言的比较。两者都能编译成跨平台,
- 代码如下:/** * 动态生成SQ及SQL参数L * @param ve 接收到的消息的CHGLIST &nbs
- Java8新特性系列我们已经介绍了Stream、Lambda表达式、DateTime日期时间处理,最后以“NullPointerExcept
- JPA like 模糊查询 语法格式public List<InstitutionInfo> getAllInstitution