美文网首页
MyBatis-Plus作为主数据源,JdbcTemplate作

MyBatis-Plus作为主数据源,JdbcTemplate作

作者: ivms8200 | 来源:发表于2023-04-02 15:48 被阅读0次

本文由AI生成
提问:springboot如何使用mybatis-plus作为主数据源,jdbctemplate作为第二个数据源

在Spring Boot中,我们可以使用多个数据源来访问不同的数据库。对于使用MyBatis-Plus和JdbcTemplate两种方式来访问主、从数据库的情况,我们可以按照以下步骤进行设置:

在application.properties文件中配置主数据源和从数据源的信息:

spring.datasource.url=jdbc:mysql://localhost:3306/primary_db
spring.datasource.username=root
spring.datasource.password=123456

spring.secondary.datasource.url=jdbc:mysql://localhost:3306/secondary_db
spring.secondary.datasource.username=root
spring.secondary.datasource.password=123456

创建主数据源的DataSource Bean,并将其配置为Primary:

@Configuration
public class DataSourceConfig {
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix="spring.secondary.datasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

配置MyBatis-Plus操作主数据源:

@Configuration
@MapperScan(basePackages = {"com.example.demo.mapper"})
public class MybatisPlusConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory;
    }
}

配置JdbcTemplate操作从数据源:

@Configuration
public class JdbcTemplateConfig {
    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

在需要访问主数据源的Service中,注入MyBatis-Plus的Mapper并使用默认的SqlSessionTemplate:

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> selectAll() {
        return userMapper.selectList(null);
    }
}

在需要访问从数据源的Repository中,注入JdbcTemplate并使用其操作从数据库:

@Repository
public class UserRepository {
    @Autowired
    @Qualifier("secondaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public List<User> findAll() {
        String sql = "SELECT * FROM secondary_db.user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    }
}

这样,我们就可以使用MyBatis-Plus和JdbcTemplate两种方式来访问不同的数据库了。注意,在此配置下,Mybatis-Plus和jdbcTemplate共用同一个事务管理器,需要逐一测试验证兼容性。

相关文章

网友评论

      本文标题:MyBatis-Plus作为主数据源,JdbcTemplate作

      本文链接:https://www.haomeiwen.com/subject/pzjrddtx.html