<div class="article">
<p>通過@<a name="baidusnap0"></a><b style="color:black;background-color:#ffff66">Configuration</b>使用MyBatis配置類的資料比較少,大部分都是通過XML的形式。找了好久,最終還是通過官方的文檔找到了解決方法:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/</p>
Using a ConfigurationCustomizer
The MyBatis-Spring-Boot-Starter provide opportunity to customize a MyBatis configuration generated by auto-configuration using Java Config. The MyBatis-Spring-Boot-Starter will search beans that implements the ConfigurationCustomizer interface by automatically, and call a method that customize a MyBatis configuration. (Available since 1.2.1 or above)For example:
// @Configuration class @Bean ConfigurationCustomizer mybatisConfigurationCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { // customize ... } }; }
但是如果你用了MyBatisPlus的話,以上代碼就可能會失效,打斷點也進不來。我是看了近半小時的源代碼才偶然發現問題所在。MybatisPlusAutoConfiguration類的sqlSessionFactory方法中有一段代碼:
MybatisConfiguration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new MybatisConfiguration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
customizer.customize(configuration);
}
}
我們可以看到這段代碼標紅的地方就是通過ConfigurationCustomizer獲取自定義配置,初看這代碼也沒什么問題,但是為什么自己寫的mybatisConfigurationCustomizer會失效呢?關鍵就在ConfigurationCustomizer,這里引用的是MyBatisPlus自定義的一個和MyBatis同名的接口,com.baomidou.mybatisplus.spring.boot.starter.ConfigurationCustomizer,因此必須使用MyBatisPlus的ConfigurationCustomizer才行,修改后代碼:
import org.apache.ibatis.type.JdbcType; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.spring.boot.starter.ConfigurationCustomizer;
@Configuration
public class MyBatisPlusConfig {@Bean public ConfigurationCustomizer configurationCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(org.apache.ibatis.session.<b style="color:black;background-color:#ffff66">Configuration</b> <b style="color:black;background-color:#ffff66">configuration</b>) { <b style="color:black;background-color:#ffff66">configuration</b>.setCacheEnabled(true); <b style="color:black;background-color:#ffff66">configuration</b>.setMapUnderscoreToCamelCase(true); <b style="color:black;background-color:#ffff66">configuration</b>.setCallSettersOnNulls(true); <b style="color:black;background-color:#ffff66">configuration</b>.setJdbcTypeForNull(JdbcType.NULL); } }; }
}
完美運行。