SSM项目整合多数据源

以双数据源为例

前言

前端时间写过一篇关于SSH项目整合多数据源,最近根据前例整合了一个SSM项目的多数据源,原理上还是一样的,但是SSM需要进行mybatis相关配置。

正文

首先还是需要配置两个数据源,这次使用的是mysql的两个不同的库,但是两个数据源一定要有区分,就像我的第二个数据源前缀加了slave。

spring:
  datasource:
    jdbc-url: jdbc:mysql://localhost:3306/homeWork?&useSSL=false&serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: 123
    password: 123
    hikari:
      connection-timeout: 60000
      maximum-pool-size: 10
  slave: #区分第二个数据源
    datasource:
      jdbc-url: jdbc:mysql://localhost:3306/area?&useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
      driver-class-name: com.mysql.cj.jdbc.Driver
      username:  123
      password: 123
      hikari:
        connection-timeout: 60000
        maximum-pool-size: 10

然后就是需要配置两个数据源文件,根据文件中数据源的前缀,创建两个数据源,并且在主数据源上指定@Primary。本次配置也是使用分包的方式,不同的数据源扫描不同的包。
主数据源配置文件:

@Configuration
@MapperScan(basePackages = "com.lcf.demo.dao", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class DataSourceConfigMaster {

    @Bean(name = "master")
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDateSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("master") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/student/*.xml"));
        return bean.getObject();
    }

    @Bean("masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(
            @Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

从数据源配置文件:

@Configuration
@MapperScan(basePackages = "com.lcf.demo.dao2", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class DataSourceConfigSavle {

    @Bean(name = "slave")
    @ConfigurationProperties(prefix = "spring.slave.datasource")
    public DataSource getDateSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slave") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/area/*.xml"));
        return bean.getObject();
    }
    @Bean("slaveSqlSessionTemplate")
    public SqlSessionTemplate slaveSqlSessionTemplate(
            @Qualifier("slaveSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

数据源配置完成,接下来就需要配置数据源相关的事务管理器和相关的连接工厂。
主数据源相关配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryMaster1",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerMaster1", //配置 事物管理器  transactionManager
        basePackages = {"com.lcf.demo.dao"}
)
public class MasterDataSourceConfig {
    @Autowired
    @Qualifier("master")
    private DataSource dataSourceMaster;
    @Autowired
    private JpaProperties jpaProperties;

    @Bean("entityManagerMaster1")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryBean(builder).getObject().createEntityManager();
    }
    @Bean("entityManagerFactoryMaster1")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSourceMaster)
                .properties(jpaProperties.getProperties())
                .packages("com.lcf.demo.bean")
                //持久化单元名称,当存在多个EntityManagerFactory时,需要制定此名称
                .persistenceUnit("masterPersistenceUnit")
                .build();

    }
    @Bean("transactionManagerMaster1")
    @Primary
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());
    }
}

从数据源相关配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryMaster2",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerMaster2", //配置 事物管理器  transactionManager
        basePackages = {"com.lcf.demo.dao2"}
)
public class SlaveDataSourceConfig {
    @Autowired
    @Qualifier("slave")
    private DataSource dataSourceSlave;
    @Autowired
    private JpaProperties jpaProperties;

    @Bean("entityManagerMaster2")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryBean(builder).getObject().createEntityManager();
    }
    @Bean("entityManagerFactoryMaster2")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSourceSlave)
                .properties(jpaProperties.getProperties())
                .packages("com.lcf.demo.bean2")
                //持久化单元名称,当存在多个EntityManagerFactory时,需要制定此名称
                .persistenceUnit("slavePersistenceUnit")
                .build();

    }
    @Bean("transactionManagerMaster2")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());
    }
}

代码中涉及的packages需要根据自己的项目修改,无非就是存放bean、存放dao层、还有就是存放mapper的文件目录。

结束

目前大家都已经稳定上班了吧,又开始了慌慌张张的上班,不过是为了碎银几两,偏偏这碎银几两,能解万千惆怅。为了这碎银几两,断了儿时的念想,让年少的我们染上了沧桑,压弯了脊梁。但这碎银可让父母安康,可护幼子成长,加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值