一、数据池
1.cp30
@Bean
public DataSource createDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try{
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUser);
dataSource.setPassword(jdbcPassword);
dataSource.setAutoCommitOnClose(false);
....
}catch (Exception e){
e.printStackTrace();
}
return dataSource;
}
2.druid
@Bean
public DataSource createDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(jdbcDriver);
druidDataSource.setUrl(jdbcUrl);
druidDataSource.setUsername(jdbcUser);
druidDataSource.setPassword(jdbcPassword);
druidDataSource.setMaxActive(20);
druidDataSource.setInitialSize(1);
druidDataSource.setMaxWait(60000);
druidDataSource.setMinIdle(1);
return druidDataSource;
}
二、SessionFactory
@Bean
public SqlSessionFactoryBean createSqlSessionFactory() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageXMLConfigPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperXMLConfigPath;
// 设置MyBatis 配置文件的路径
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(myBatisConfigPath));
// 设置mapper 对应的XML 文件的路径
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageXMLConfigPath));
// 设置数据源
sqlSessionFactoryBean.setDataSource(createDataSource());
// 设置mapper 接口所在的包
sqlSessionFactoryBean.setTypeAliasesPackage(mapperPackagePath);
return sqlSessionFactoryBean;
}
三、事务
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(createDataSource());
}
@Configuration
@EnableTransactionManagement //开启事务 <tx:annotation-driven/>
public class TransactionManagementConfiguration implements TransactionManagementConfigurer {
@Autowired
private DataSource dataSource;
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}