1. 程式人生 > >SpringBoot的MyBatis的配置類

SpringBoot的MyBatis的配置類

一 資料來源配置

package com.imooc.demo.config.dao;

import java.beans.PropertyVetoException;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
* 配置datasource到ioc容器裡面
*/
@Configuration
// 配置mybatis mapper的掃描路徑
@MapperScan("com.imooc.demo.dao")
public class DataSourceConfiguration {
    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    /**
     * 生成與spring-dao.xml對應的bean dataSource
     *
     * @return
     * @throws PropertyVetoException
     */
    @Bean(name = "dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        // 生成datasource例項
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        // 跟配置檔案一樣設定以下資訊
        // 驅動
        dataSource.setDriverClass(jdbcDriver);
        // 資料庫連線URL
        dataSource.setJdbcUrl(jdbcUrl);
        // 設定使用者名稱
        dataSource.setUser(jdbcUsername);
        // 設定使用者密碼
        dataSource.setPassword(jdbcPassword);
        // 配置c3p0連線池的私有屬性
        // 連線池最大執行緒數
        dataSource.setMaxPoolSize(30);
        // 連線池最小執行緒數
        dataSource.setMinPoolSize(10);
        // 關閉連線後不自動commit
        dataSource.setAutoCommitOnClose(false);
        // 連線超時時間
        dataSource.setCheckoutTimeout(10000);
        // 連線失敗重試次數
        dataSource.setAcquireRetryAttempts(2);
        return dataSource;
    }

}

二 會話工廠配置

package com.imooc.demo.config.dao;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
public class SessionFactoryConfiguration {
    // mybatis-config.xml配置檔案的路徑
    private static String mybatisConfigFile;

    @Value("${mybatis_config_file}")
    public void setMybatisConfigFile(String mybatisConfigFile) {
        SessionFactoryConfiguration.mybatisConfigFile = mybatisConfigFile;
    }

    // mybatis mapper檔案所在路徑
    private static String mapperPath;

    @Value("${mapper_path}")
    public void setMapperPath(String mapperPath) {
        SessionFactoryConfiguration.mapperPath = mapperPath;
    }

    // 實體類所在的package
    @Value("${type_alias_package}")
    private String typeAliasPackage;

    @Autowired
    private DataSource dataSource;

    /**
     * 建立sqlSessionFactoryBean 例項 並且設定configtion 設定mapper 對映路徑 設定datasource資料來源
     *
     * @return
     * @throws IOException
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 設定mybatis configuration 掃描路徑
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile));
        // 新增mapper 掃描路徑
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        // 設定dataSource
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 設定typeAlias 包掃描路徑
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
        return sqlSessionFactoryBean;
    }

}

三 事務配置

package com.imooc.demo.config.service;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/**
* 對標spring-service裡面的transactionManager
* 繼承TransactionManagementConfigurer是因為開啟annotation-driven

*
*/
@Configuration
// 首先使用註解 @EnableTransactionManagement 開啟事務支援後
// 在Service方法上添加註解 @Transactional 便可
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer {

    @Autowired
    // 注入DataSourceConfiguration裡邊的dataSource,通過createDataSource()獲取
    private DataSource dataSource;

    @Override
    /**
     * 關於事務管理,需要返回PlatformTransactionManager的實現
     */
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

}