Spring Java 注解配置之 数据源配置

使用的数据源为:阿里的Druid数据源,mysql-connect版本是8.x.x,在查询上使用的是MyBatis,并配置了:PageHelper(分页拦截器)、通用Mapper。

需要配置jdbc.properties文件:

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/schema?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&nullCatalogMeansCurrent=true
jdbc.username=root
jdbc.password=root

注:在使用mysql-connect 8.+以上版本的时候需要添加nullCatalogMeansCurrent=true参数,否则在使用mybatis-generator生成表对应的xml等时会扫描整个服务器里面的全部数据库中的表,而不是扫描对应数据库的表。

JAVA配置类:

@Configuration
@EnableTransactionManagement
@ComponentScan("cn.virens.database.serviceimpl")
public class SpringDataSourceConfig {
    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String jdbcUsername;

    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Value("${jdbc.driverClass}")
    private String jdbcDriverClass;

    /**
     * mysql事务管理
     * 
     * @return
     */
    @Bean(name = "txManager")
    public PlatformTransactionManager txManager(@Qualifier("druidDataSource") DruidDataSource druidDataSource) {
        return new DataSourceTransactionManager(druidDataSource);
    }

    @Bean(name = "txExecute")
    public TransactionExecute txExecute(@Qualifier("txManager") PlatformTransactionManager manager) {
        return new TransactionExecute(manager);
    }

    /**
     * MyBatis 数据连接地址池配置
     * 
     * @throws IOException
     * @throws SQLException
     */
    @Bean(name = "druidDataSource", destroyMethod = "close")
    public DruidDataSource druidDataSource(Environment env) throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        dataSource.setDriverClassName(jdbcDriverClass);
        // 配置初始化大小、最小、最大
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);// 配置获取连接等待超时的时间

        dataSource.setTimeBetweenEvictionRunsMillis(60000);// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(300000);// 配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setDefaultAutoCommit(false);// 禁止自动提交,实现事务管理

        dataSource.setValidationQuery("SELECT 1;");
        dataSource.setValidationQueryTimeout(30000);

        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);

        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(50);

        // 拦截配置
        dataSource.setFilters("stat,wall");

        return dataSource;
    }

    /**
     * MyBatis配置 :配置sqlSessionFactory
     * 
     * @return
     * @throws Exception
     */
    @Bean("sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource druidDataSource) throws Exception {
        // 分页拦截器
        PageInterceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.put("helperDialect", "mysql");

        interceptor.setProperties(properties);

        // 创建SqlSession工厂
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(druidDataSource);
        sqlSessionFactoryBean.setPlugins(new Interceptor[] { interceptor });
        sqlSessionFactoryBean.setMapperLocations(ResourceUtil.getResources("classpath:mysql/**/*.xml"));

        return sqlSessionFactoryBean;
    }

    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        mapperScannerConfigurer.setBasePackage("cn.virens.database.mysql.mapper");
        mapperScannerConfigurer.getMapperHelper().getConfig().setIDENTITY("MYSQL");
        mapperScannerConfigurer.getMapperHelper().getConfig().setStyle(Style.normal);
        mapperScannerConfigurer.getMapperHelper().getConfig().setWrapKeyword("`{0}`");

        return mapperScannerConfigurer;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容