通过mybatis或JPA进行多数据源连接

数据库

package com.example.db.config;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class BaseDBConfig {
    private String username;
    private String url;
    private String password;
    private String driverClassName;
    private boolean testOnBorrow;
    private String validationQuery;
}

  • 默认数据库defaultDB
package com.example.db.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DBDefaultConfig extends BaseDBConfig{
}

  • DEV数据库devDB
package com.example.db.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "db.dev")
public class DBDevConfig extends BaseDBConfig {
}

mybatis连接数据库

  • 数据源配置
* @Primary 优先选择这个Bean,多数据源时必须通过@Primary配置主数据源
* @MapperScan 扫描 Mapper 接口,确定需要被扫描的包, 与其他数据进行区分
* sqlSessionFactoryRef 表示定义了 key ,表示一个唯一 SqlSessionFactory 实例
package com.example.db.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.example.db.dao.mybatis"},sqlSessionFactoryRef = "mybatisSqlSessionFactory")
public class DataSourceConfigMybtis {
    @Autowired
    DBDefaultConfig dbDefaultConfig;

    @Primary
    @Bean("mybatisDataSource")
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dbDefaultConfig.getDriverClassName());
        dataSource.setUsername(dbDefaultConfig.getUsername());
        dataSource.setPassword(dbDefaultConfig.getPassword());
		dataSource.setUrl(dbDefaultConfig.getUrl());
		dataSource.setValidationQuery(dbDefaultConfig.getValidationQuery());
        return dataSource;
    }

    @Bean("mybatisSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mybatisDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //mapper.xml文件的存放路径,比如resources下的mapper文件夹
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("mybatisTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("mybatisDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("mybatisSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mybatisSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

JPA连接数据库

  • 数据源配置
package com.example.db.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
                        transactionManagerRef = "jpaTransactionManager",
                        basePackages = {"com.example.db.dao.jpa"})
public class DataSourceConfigJPA {
    @Autowired
    private DBDevConfig dbDevConfig;
    @Autowired
    private JpaProperties jpaProperties;

    @Bean("jpaDataSource")
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dbDevConfig.getDriverClassName());
        dataSource.setUsername(dbDevConfig.getUsername());
        dataSource.setPassword(dbDevConfig.getPassword());
        dataSource.setUrl(dbDefaultConfig.getUrl());
		dataSource.setValidationQuery(dbDefaultConfig.getValidationQuery());
        return dataSource;
    }

    @Bean("entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder entityManagerFactoryBuilder,
                                                                       @Qualifier("jpaDataSource") DataSource dataSource){
        return entityManagerFactoryBuilder.dataSource(dataSource)
                                          .properties(jpaProperties.getProperties())
                                          .packages("com.example.db.bean.jpa") //实体类存放package
                                          .build();
    }

    public EntityManager entityManager(@Qualifier("entityManagerFactory") LocalContainerEntityManagerFactoryBean entityManagerFactory){
        return entityManagerFactory.getObject().createEntityManager();
    }

    @Bean("jpaTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") LocalContainerEntityManagerFactoryBean entityManagerFactory){
        return new JpaTransactionManager(entityManagerFactory.getObject());
    }


}

注意事项

  • 在service层需要在@Transctional中添加transactionManager的名字,比如:@Transctional(transactionManager=“jpaTransactionManager”)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值