使用场景:
使用多数据源时,自定义创建SqlSessionFactory对象,没有正确读取到mybatis-config.xml配置,导致下划线驼峰映射失效,sql语句输出不显示等问题。
解决方案:
@Bean(name = "UserSqlSessionFactory")
public SqlSessionFactory dataLgSqlSessionFactory(@Qualifier("UserDataDataSource") DataSource dataSource, MybatisProperties mybatisProperties) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user/**/*.xml"));
bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
return bean.getObject();
}
mybatis-config.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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/> <!-- 按需加载对象 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="useGeneratedKeys" value="true"/>
</settings>
</configuration>