MyBatis整合到SpringBoot的两种方式
MyBatis可以通过两种常见的方式整合到Spring Boot中:
使用Spring Boot的自动配置特性:
在
pom.xml
中添加Spring Boot的MyBatis起步依赖,例如:<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
然后在
application.properties
或application.yml
中配置MyBatis相关设置。手动配置:
在
pom.xml
中添加MyBatis和MySQL(或其他数据库)的依赖:<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency>
在
application.properties
或application.yml
中配置数据源,并通过Java配置类配置MyBatis的SqlSessionFactory和Mapper接口。
以下是一个简单的Java配置类示例,演示如何手动配置MyBatis:
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean.getObject();
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
dataSource.setUsername("myuser");
dataSource.setPassword("mypassword");
return dataSource;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePac
评论已关闭