【Spring教程12】Spring框架实战:Spring整合Mybatis全面深入详解
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 可以设置更多的MyBatis全局配置 like 'mapperLocations' and 'configLocation'
return sqlSessionFactoryBean.getObject();
}
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myapp");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.myapp.mapper");
return mapperScannerConfigurer;
}
}
这个配置类展示了如何在Spring中配置MyBatis的SqlSessionFactory、DataSource以及自动扫描Mapper接口。这是一个基本的配置模板,可以根据实际情况进行调整和扩展。
评论已关闭