springboot 获取SqlSessionFactory 列表
时间: 2024-01-18 07:04:55 浏览: 221
SpringBoot+MyBatis+SqlSession
根据提供的引用内容,获取Spring Boot中的SqlSessionFactory实例的步骤如下:
1. 首先,确保在pom.xml文件中添加了相关的依赖版本,如下所示:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>
```
2. 在Spring Boot的配置文件(application.properties或application.yml)中配置数据源信息,例如:
```yaml
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
```
3. 创建一个配置类,用于配置MyBatis的SqlSessionFactory实例,例如:
```java
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class MyBatisConfig {
@Autowired
private DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return sessionFactory.getObject();
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
dataSource.setUsername("root");
dataSource.setPassword("123456");
return dataSource;
}
}
```
4. 在需要使用SqlSessionFactory的地方,注入SqlSessionFactory实例,并使用它来获取mapper接口实例,例如:
```java
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class MyRepository {
private final SqlSessionTemplate sqlSessionTemplate;
@Autowired
public MyRepository(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
}
public void doSomething() {
MyMapper myMapper = sqlSessionTemplate.getMapper(MyMapper.class);
// 使用myMapper进行数据库操作
}
}
```
以上是获取Spring Boot中的SqlSessionFactory实例的步骤。通过配置数据源和SqlSessionFactory,我们可以使用MyBatis的mapper接口实例来操作数据库。
阅读全文