mybatis-plus中修改SqlSession配置的数据源
时间: 2024-05-03 11:23:11 浏览: 104
springboot+mybatisPlus+mysql动态数据源切换
可以通过实现`org.apache.ibatis.session.SqlSessionFactoryBuilder`接口,并在其中设置数据源,然后用该实现类来创建`SqlSessionFactory`对象,从而实现修改`SqlSession`配置的数据源。
具体代码如下:
```
public class MybatisPlusSqlSessionFactoryBuilder implements SqlSessionFactoryBuilder {
private DataSource dataSource;
public MybatisPlusSqlSessionFactoryBuilder(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public SqlSessionFactory build(Configuration configuration) {
Environment environment = new Environment("mybatis-plus", new JdbcTransactionFactory(), dataSource);
configuration.setEnvironment(environment);
return new DefaultSqlSessionFactory(configuration);
}
}
```
然后,在使用`SqlSessionFactoryBuilder`创建`SqlSessionFactory`时,传入`MybatisPlusSqlSessionFactoryBuilder`对象即可:
```
DataSource dataSource = new MyDataSource();
Configuration configuration = new Configuration();
MybatisPlusSqlSessionFactoryBuilder builder = new MybatisPlusSqlSessionFactoryBuilder(dataSource);
SqlSessionFactory sessionFactory = builder.build(configuration);
SqlSession sqlSession = sessionFactory.openSession();
```
这样,`SqlSession`就会使用`MyDataSource`作为数据源了。
阅读全文