之前我们在写mybatis-config.xml的时候是这么写的
<environments default="MyBatisLearning">
<environment id="MyBatisLearning">
<!-- 配置当前环境的事务管理-->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据源,也就是要跟哪个数据库链接-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/tx"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
当整合了SpringMVC之后,我们就可以用xml或注解(推荐)的方式
/**
* 配置数据源
*/
@Configuration
public class DataSourceConfig {
@Value("${DataSource}")
private String DataSource;
@Bean(name = "dataSource")
public DataSource dataSource() {
return DataSourceBuilder.build();
}
}
/**
* 根据数据源配置事务管理器
*/
@Configuration
public class TransactionManagerConfig {
@Bean(name="TransactionManager")
public PlatformTransactionManager TransactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
/**
* 根据数据源配置Mybatis
* MapperScan注解可以帮助配置mapper.xml需要扫描的DAO,具体的sqlSessionFactory和sqlSessionTemplate
* 注意用这种方式,sqlSessionFactory是使用SqlSessionFactoryBean来帮忙创建的
*/
@Configuration
@MapperScan(basePackages = "com.test.dao", sqlSessionFactoryRef = "sqlSessionFactory", sqlSessionTemplateRef = "sqlSessionTemplate")
public class MyBatisConfig {
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource,
@Value("classpath:mybatis/mybatis-config.xml") Resource configLocation) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setConfigLocation(configLocation);
return sqlSessionFactoryBean.getObject();
}
@Bean(name = "sqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/20571.html