Springboot jpa 配置多数据源

  • Post author:
  • Post category:其他

因为项目中使用的分布式开发模式,不同的服务有不同的数据源,所以需要多个数据源支持,因此配置sping data jpa对多数据源的使用:

1 配置多数据源
2 不同数据源的实体类放入不同包路径
3 不同数据源的EntityManager的注入方法
4 声明不同数据源的事务支持

数据源配置

spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/a_task
spring.datasource.primary.username=admin
spring.datasource.primary.password=123
spring.datasource.primary.hibernate.ddl-auto=none
spring.datasource.primary.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.primary.hibernate.show-sql=true


spring.datasource.second.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.second.jdbc-url=jdbc:sqlserver://localhost:58923;DatabaseName=b_task
spring.datasource.second.username=admin
spring.datasource.second.password=123
spring.datasource.second.hibernate.ddl-auto=none
spring.datasource.second.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect
spring.datasource.second.hibernate.show-sql=true

DataSource相关配置


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= { "com.x3.server.plat.table.primary" }) //设置Repository所在位置
public class PrimaryConfig {
	
	@Primary
	@Bean(name = "Primary")
	@Qualifier("Primary")
	@ConfigurationProperties(prefix = "spring.datasource.primary")
	public DataSource getPrimaryDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Value("${spring.datasource.primary.hibernate.dialect}")
    private String primaryDialect;

	@Value("${spring.datasource.primary.hibernate.ddl-auto}")
    private String ddlAuto;
	
	@Value("${spring.datasource.primary.hibernate.show-sql}")
    private boolean showSql;
	
    @Bean(name = "entityManagerFactoryPrimary")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(getPrimaryDataSource());
        em.setPackagesToScan(new String[] { "com.x3.server.plat.table.primary" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",ddlAuto);
        properties.put("hibernate.dialect",primaryDialect);
        properties.put("hibernate.show_sql",showSql);
        
        em.setJpaPropertyMap(properties);
        return em;
    }
    
    
    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary() {
    	JpaTransactionManager transactionManager = new JpaTransactionManager();
    	transactionManager.setEntityManagerFactory( entityManagerFactoryPrimary().getObject());
    	return transactionManager;
    }
	
}


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecond",
        transactionManagerRef="transactionManagerSecond",
        basePackages= { "com.x3.server.plat.table.second" }) //设置Repository所在位置
public class SecondConfig {
	

	@Bean(name = "Second")
	@Qualifier("Second")
	@ConfigurationProperties(prefix = "spring.datasource.second")
	public DataSource getSecondDataSource() {
		return DataSourceBuilder.create().build();
	}
	
	@Value("${spring.datasource.second.hibernate.dialect}")
    private String primaryDialect;
	
	@Value("${spring.datasource.second.hibernate.ddl-auto}")
    private String ddlAuto;

	@Value("${spring.datasource.second.hibernate.show-sql}")
    private boolean showSql;
	
    @Bean(name = "entityManagerFactorySecond")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(getSecondDataSource());
        em.setPackagesToScan( new String[] { "com.x3.server.plat.table.second" });

        HibernateJpaVendorAdapter vendorAdapter  = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",ddlAuto);
        properties.put("hibernate.dialect",primaryDialect);
        properties.put("hibernate.show_sql",showSql);
        
        em.setJpaPropertyMap(properties);
        

        return em;
    }
    
    
    @Bean(name = "transactionManagerSecond")
    public PlatformTransactionManager transactionManagerSecond() {
    	JpaTransactionManager transactionManager = new JpaTransactionManager();
    	transactionManager.setEntityManagerFactory( entityManagerFactorySecond().getObject());
    	return transactionManager;
    }
	
}

实体类

数据源一:

package com.x3.server.plat.table.primary;

@Getter
@Setter
@Entity
@Table(name = "task_user")
public class UserTable implements Serializable  {
	private static final long serialVersionUID = 1L;
	
	@Id
	@Column(name="user_id",nullable=false,length=32)
	private String userId;
	@Column(name="user_code",length=50)
	private String userCode;
}

数据源二:

package com.x3.server.plat.table.second;

@Getter
@Setter
@Entity
@Table(name = "p_work")
public class WorkTable implements Serializable  {

	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="cvnid",nullable=false,length=32)
	private int cvnId;
	@Column(name="cvntitle")
	private String cvnTitle;
}

EntityManager数据源注入


	@Autowired
	@Qualifier("entityManagerFactorySecond")
	private EntityManager em;

事务配置


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class, BusinessException.class,
		Exception.class}, timeout = 60, value = "transactionManagerPrimary")
public @interface TransactionalPrimary {
	
}


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RuntimeException.class, BusinessException.class,
		Exception.class}, timeout = 60, value = "transactionManagerSecond")
public @interface TransactionalSecond {
}



版权声明:本文为gust150原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。