三、mybatis和数据库及事务的配置:
package com.io.ssm.framework.config; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.SqlSessionFactoryBean; import org.mybatis.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.interceptor.TransactionInterceptor; import javax.sql.DataSource; import java.io.IOException; import java.sql.SQLException; import java.util.Properties; /** * @author lvyongb. * @Description Druid数据库连接配置 * @date 2018/4/27. */ @Configuration @MapperScan(basePackages="com.io.ssm.module.domain") @PropertySources({@PropertySource(("classpath:jdbc.properties"))}) public class DruidDataSourceConfig { private final static Logger LOG = LoggerFactory.getLogger(DruidDataSourceConfig.class); @Value("${datasource.url}") private String dbUrl; @Value("${datasource.username}") private String username; @Value("${datasource.password}") private String password; @Value("${datasource.driverClassName}") private String driverClassName; @Value("${datasource.initialSize}") private int initialSize; @Value("${datasource.minIdle}") private int minIdle; @Value("${datasource.maxActive}") private int maxActive; @Value("${datasource.maxWait}") private int maxWait; @Value("${datasource.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${datasource.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${datasource.validationQuery}") private String validationQuery; @Value("${datasource.testWhileIdle}") private boolean testWhileIdle; @Value("${datasource.testOnBorrow}") private boolean testOnBorrow; @Value("${datasource.testOnReturn}") private boolean testOnReturn; @Value("${datasource.poolPreparedStatements}") private boolean poolPreparedStatements; @Value("${datasource.maxPoolPreparedStatementPerConnectionSize}") private int maxPoolPreparedStatementPerConnectionSize; @Value("${datasource.filters}") private String filters; @Value("{datasource.connectionProperties}") private String connectionProperties; @Bean public DataSource dataSource() { LOG.info("------------------dataSource初始化--------------"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(this.dbUrl); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); //configuration datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); datasource.setPoolPreparedStatements(poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); try { datasource.setFilters(filters); } catch (SQLException e) { LOG.error("druid configuration initialization filter----->>:", e); } datasource.setConnectionProperties(connectionProperties); return datasource; } /** * mybatis的配置 * @return */ private org.apache.ibatis.session.Configuration getMybatisConfiguration() { org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis .session.Configuration(); configuration.setCacheEnabled(true); configuration.setDefaultStatementTimeout(3000); configuration.setMapUnderscoreToCamelCase(true); configuration.setUseGeneratedKeys(true); configuration.setUseColumnLabel(true); return configuration; } @Bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); try { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setConfiguration(getMybatisConfiguration()); sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver .getResources("classpath*:com/io/ssm/module/domain/*Mapper.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.io.ssm.module.domain"); } catch (IOException e) { LOG.error("SqlSessionFactoryBean configuration exception ----->>:", e); } return sqlSessionFactoryBean; } /** * 此方式和@MapperScan("com.io.ssm.module.domain")注解功能一样,可以互换 * @return */ /*@Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer mScannerConfigurer = new MapperScannerConfigurer(); mScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mScannerConfigurer.setBasePackage("com.io.ssm.module.domain"); return mScannerConfigurer; }*/ /** * 事务控制配置 * @return */ @Bean(name = "transactionManager") public DataSourceTransactionManager dataSourceTransactionManager(){ DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource()); return dataSourceTransactionManager; } @Bean(name="transactionInterceptor") public TransactionInterceptor interceptor(){ TransactionInterceptor interceptor = new TransactionInterceptor(); interceptor.setTransactionManager(dataSourceTransactionManager()); Properties transactionAttributes = new Properties(); transactionAttributes.setProperty("*","PROPAGATION_REQUIRED"); interceptor.setTransactionAttributes(transactionAttributes); return interceptor; } }
事务配置简单的方式可以采用在 RootConfig 加上@EnableTransactionManagement 注解,
再加上配置 DataSourceTransactionManager 的bean,就可以在service实现层使用 @Transactional 注解即可
jdbc的配置文件:
#mysql datasource.type=com.alibaba.druid.pool.DruidDataSource datasource.driverClassName=com.mysql.jdbc.Driver #因为此项目中引入的是mysql-connector-java 6.0.6,所以需要添加时区参数 datasource.url=jdbc:mysql://localhost:3308/db_pms?useUnicode=true\ &characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC #datasource.url=jdbc:mysql://localhost:3308/db_pms?useUnicode=true&characterEncoding=utf8 datasource.username=root datasource.password=root #连接池配置 datasource.initialSize=5 datasource.minIdle=5 datasource.maxActive=20 #连接等待超时时间 datasource.maxWait=60000 #配置隔多久进行一次检测(检测可以关闭的空闲连接) datasource.timeBetweenEvictionRunsMillis=60000 #配置连接在池中的最小生存时间 datasource.minEvictableIdleTimeMillis=300000 datasource.validationQuery=SELECT 1 FROM DUAL datasource.testWhileIdle=true datasource.testOnBorrow=false datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 datasource.poolPreparedStatements=true datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000