Springboot + jpa + PG
- springboot JPA + PostGreSQL ```yaml
spring: datasource: url: jdbc:postgresql://localhost:5432/testdb username: pg password: pg driver-class-name: org.postgresql.Driver
jpa: hibernate: ddl-auto: update show-sql: true
<a name="uda8h"></a>
# 多数据源
```yaml
spring:
datasource:
primary:
jdbc-url: jdbc:mysql://localhost:3306/jpa?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
jdbc-url: jdbc:postgresql://localhost:5432/testdb
username: pg
password: pg
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
# 暂时都用mysql方言,理论上应分配配置
dialect: org.hibernate.dialect.MySQLDialect
DynamicDataSource, AOP切换数据源
- Mybatis, SpringBoot多数据源配置MySQL和PostgreSQL同时使用
常规Spring分别配置dataSource、sqlSessionFactory、transactionManger
-
事务问题
SpringBoot+Mybatis配置多数据源及事务方案
SpringBoot多数据源中的分布式事务
JPA多数据源分布式事务处理-两种事务方案: XA事务方案,链式事务方案
试验结论:当前用的是哪个事务,就作用于哪个的插入链式事务
[x] ChainedTransactionManager 无法保证完全一致性,建议用TransactionSynchronization替代
- Spring事务管理(二)分布式事务管理之JTA与链式事务
放置的顺序先userTM后resultTM,所以事务应该是先拿到userTM然后拿到resultTM然后提交resultTM最后提交userTM,也就是说,如果我在提交user事务的时候出错,此时result相关的事务已经提交完成,所以result数据是不能回滚的。
注意:所谓的“在提交user事务的时候出错”,是指commit出错,比如数据库断电。而业务抛出异常、数据库操作异常(例如字段缺失),也是可以全部回滚的。
试验结果:
1. 任何位置代码抛出的异常,所有事务都可以回滚
2. 如果第一个commit的连接出现问题,可以一起回滚
3. 如果第二个commit的连接出现问题,只有第二个回滚(sybase不回滚,mysql回滚)
分库分表
- 实战 PostgreSQL 分区表
-- 如果在表名前指定了 ONLY,则只会扫描该表。如果没有指定ONLY,该表及其所有后代表(如果有)都会被扫描。
-- 可选地,可以在表名后指定*来显式地指示包括后代表。
SELECT COUNT(1) FROM only native_emp;