關於springboot中對sqlSessionFactoryBean的自定義

springboot sqlSessionFactoryBean自定義

1.新建一個配置類,加上configuration註解

2.定制化SqlSessionFactoryBean,然後交給容器管理

代碼如下

@Configuration
public class MybatisConfig {
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    @Bean
    public SqlSessionFactoryBean configSqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // configuration.setLogImpl(StdOutImpl.class);//標準輸出日志
        configuration.setLogImpl(NoLoggingImpl.class);// 不輸出日志()
        configuration.setMapUnderscoreToCamelCase(true);// 開啟駝峰命名
        configuration.setCallSettersOnNulls(true);// 開啟在屬性為null也調用setter方法

        sqlSessionFactoryBean.setConfiguration(configuration);
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));// 設置mapper文件掃描路徑
        return sqlSessionFactoryBean;
    }

以上配置也可以通過properties文件配置

如:

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis.configuration.mapUnderscoreToCamelCase=true
mybatis.configuration.call-setters-on-nulls=true

springboot啟動報找不到sqlSessionFactory

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sqlSessionFactory’ defined in class path resource [com/baomidou/mybatisplus/spring/boot/starter/MybatisPlusAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method ‘sqlSessionFactory’ threw exception; nested exception is com.baomidou.mybatisplus.exceptions.MybatisPlusException: Error: GlobalConfigUtils setMetaData Fail ! Cause:java.sql.SQLException: oracle.jdbc.OracleDriver

原因是這個電腦 ,這個項目第一次啟動,項目鏈接的是Oracle的數據庫,Oracle沒把自己jar包放在maven庫,要自己安裝

在maven倉庫目錄下 放置Oracle的jar包

再在cmd中切換到 這個目錄下運行命令:

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.4.0 -Dpackaging=jar -Dfile=ojdbc14.jar

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: