Springboot jpa 配置多数据源

因为项目中使用的分布式开发模式,不同的服务有不同的数据源,所以需要多个数据源支持,因此配置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 {
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中配置JPA多数据源的方法如下: 1. 首先,在pom.xml文件中添加必要的依赖项,包括Spring Boot、JPA和数据库驱动程序。 2. 创建对应的数据源配置类,包括数据库连接信息、用户名、密码等。可以创建多个数据源配置类,每个数据源对应一个数据库。 3. 创建对应的JdbcTemplate实例,用于在代码中执行SQL语句。每个数据源都需要创建一个对应的JdbcTemplate对象。 4. 创建指定数据源的方法,用于在代码中动态切换数据源。可以使用@Primary注解指定默认的数据源。 5. 创建Jpa事务管理器,用于管理多个数据源的事务。每个数据源都需要创建一个对应的Jpa事务管理器。 6. 使用AOP的切面来切换数据源。可以使用@Before和@After注解来分别在方法执行前和执行后进行数据源的切换和恢复。 以上是配置JPA多数据源的一般步骤,根据具体需求和情况,可能还需要进行一些额外的配置和调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot-JPA多数据源](https://blog.csdn.net/zZZ251682553/article/details/125105388)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot jpa 多数据源配置](https://blog.csdn.net/chenxing1990/article/details/122808525)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值