springboot+mybatis 多数据源(含事务)

本文介绍了如何在SpringBoot项目中结合Mybatis实现多数据源配置,详细讲解了配置文件和关键设置,包括不同SqlSessionFactory对应的不同XML文件,以及@MapperScan的使用。同时,文章提及了Service层的事务管理,特别是第二个数据源使用事务时指定TransactionManager的重要性,还分享了项目启动时可能遇到的问题和解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.配置文件

server.port=9000
spring.application.name=springboot


mybatis.type-aliases-package=olading.springboot.springboot.entity

spring.datasource.p.driverClassName = com.mysql.jdbc.Driver
//注意,一定是jdbc-url,否则系统启动异常
spring.datasource.p.jdbc-url =jdbc:mysql://localhost/root?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.p.username = root
spring.datasource.p.password = root
//这里第二个数据源利用了相同的配置,懒得替换了
spring.datasource.s.driverClassName = com.mysql.jdbc.Driver
spring.datasource.s.jdbc-url =jdbc:mysql://localhost/root?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.s.username = root
spring.datasource.s.password = root


mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

2. 配置(关键)

@Configuration
@MapperScan(basePackages = "olading.springboot.springboot.mapper.p",sqlSessionTemplateRef ="pSqlSessionTemplate" )
@MapperScan(basePackages = "olading.springboot.springboot.mapper.s",sqlSessionTemplateRef = "sSqlSessionTemplate")
public class MyConfig {
   
   
    @Bean(name = "pDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.p")
    @Primary
    public DataSource pDataSource() {
   
   
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "pSqlSessionFactory")
    @Primary
    public SqlSessionFactory pSqlSessionFactory(@Qualifier("pDataSource")DataSource dataSource) throws Exception {
   
   
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值