前面记录过Mybatis的多数据源,最近有定时清除各种记录需要用到多数据源,这里决定采用Jpa
本文主要记录Jpa多数据源的配置与使用
1.环境准备
基于spring-boot-starter-parent 2.6.8
,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--Mysql依赖包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.yaml配置
spring:
#配置 Jpa
jpa:
hibernate:
ddl-auto: update
dialect: org.hibernate.dialect.MySQL8Dialect
open-in-view: false
show-sql: true
#自定义连接
datasource:
channel:
driverClassName: com.mysql.cj.jdbc.Driver
jdbcUrl: jdbc:mysql://192.168.0.100:3306/a_channel?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
channel1:
driverClassName: com.mysql.cj.jdbc.Driver
jdbcUrl: jdbc:mysql://192.168.0.100:3306/a_channel1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
3.连接代码
@Configuration
@EnableTransactionManagement
//扫描的repository接口实现类 也就是mapper接口类
@EnableJpaRepositories(basePackages = "com.example.demo.repository.channel",
entityManagerFactoryRef = "channelEntityManagerFactory",
transactionManagerRef = "channelTransactionManager")
public class ChannelDatasourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
//数据库连接配置
@Primary
@Bean("channelDataSource")
@ConfigurationProperties(prefix = "datasource.channel")
public DataSource channelDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "entityManagerPrimary")
public EntityManager channelEntityManager(EntityManagerFactoryBuilder builder) {
return channelEntityManagerFactory(builder).getObject().createEntityManager();
}
@Bean(name = "channelEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean channelEntityManagerFactory(EntityManagerFactoryBuilder builder) {
DataSource dataSource = channelDataSource();
LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
.dataSource(dataSource)
.properties(hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(), new HibernateSettings()))
//扫描Entity的目录
.packages("com.example.demo.entity.channel")
//别名 需要唯一
.persistenceUnit("channelUnit")
.build();
return entityManagerFactory;
}
//事务
@Primary
@Bean("channelTransactionManager")
public PlatformTransactionManager channelTransactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(channelEntityManagerFactory(builder).getObject());
}
}
其他数据源复制即可,但需要注意@Primary
标签必须有且只能有一个,加上此注解的表示对应对象的默认值
4.使用
正常注解使用,在一个事务中如果同时操作两个库更新,取决于注解的事务类,默认的@Transactional
使用的是加了@Primary
注解的数据源事务管理器,也可选择传参@Transactional(value="xxxx")
来指定使用某个数据源事务管理
如果需要事务合并的需要使用到第三方事务管理包,在mybatis第二话 - mybatis,多数据源的快乐你懂吗?有详细说明
以上就是本章的全部内容了。
上一篇:Jpa第一话 – Springboot集成Jpa以及Jpa的最全使用
下一篇:Swagger第一话 – Springboot集成Swagger及使用
读书有三到,谓心到,眼到,口到