JPA多源數據庫配置(達夢數據庫)
本篇文章主要介紹SpringBoot框架實現Jpa多源數據庫的配置,本次使用國產數據庫達夢數據庫作爲數據源。spring
1.準備工做
在pom.xml文件中引入Spring Data Jpa依賴:sql
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
在application.yml中添加數據庫的相關配置:數據庫
spring: datasource: one: driver-class-name: dm.jdbc.driver.DmDriver url: jdbc:dm://127.0.0.1:5236/TESTONE username: TESTONE password: 1234567890 type: com.alibaba.druid.pool.DruidDataSource two: driver-class-name: dm.jdbc.driver.DmDriver url: jdbc:dm://127.0.0.1:5237/TESTTWO username: TESTTWO password: 1234567890 type: com.alibaba.druid.pool.DruidDataSource jpa: properties: hibernate.dialect: org.hibernate.dialect.Oracle10gDialect show-sql: ture
編寫DataSourceConfig配置文件:數組
@Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.one") @Primary DataSource dsOne(){ return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.two") DataSource dsTwo(){ return DruidDataSourceBuilder.create().build(); } }
2.建立JPA配置
根據配置好的數據源建立兩個不一樣的JPA配置,代碼以下(示例):
第一個jpa配置:
app
@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "org.xiaoyang.dao1",//持久層路徑 entityManagerFactoryRef = "entityManagerFactoryBeanOne", transactionManagerRef = "platformTransactionManagerOne") public class JpaConfigOne { @Resource(name = "dsOne") DataSource dsOne; @Autowired JpaProperties jpaProperties; @Bean @Primary LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanOne(EntityManagerFactoryBuilder builder){ return builder.dataSource(dsOne) .properties(jpaProperties.getProperties()) .packages("org.xiaoyang.entity")//實體類路徑 .persistenceUnit("pu1") .build(); } @Bean PlatformTransactionManager platformTransactionManagerOne(EntityManagerFactoryBuilder builder){ LocalContainerEntityManagerFactoryBean factoryOne = entityManagerFactoryBeanOne(builder); return new JpaTransactionManager(factoryOne.getObject()); } }
第二個jpa配置:框架
@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "org.xiaoyang.dao2",//持久層路徑 entityManagerFactoryRef = "entityManagerFactoryBeanTwo", transactionManagerRef = "platformTransactionManagerTwo") public class JpaConfigOne { @Resource(name = "dsTwo") DataSource dsTwo; @Autowired JpaProperties jpaProperties; @Bean LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanTwo(EntityManagerFactoryBuilder builder){ return builder.dataSource(dsTwo) .properties(jpaProperties.getProperties()) .packages("org.xiaoyang.entity")//實體類路徑 .persistenceUnit("pu1") .build(); } @Bean PlatformTransactionManager platformTransactionManagerTwo(EntityManagerFactoryBuilder builder){ LocalContainerEntityManagerFactoryBean factoryOne = entityManagerFactoryBeanTwo(builder); return new JpaTransactionManager(factoryOne.getObject()); } }
3.建立實體類
在org.xiaoyang.entity包(包路徑必定要和JPA配置類中的路徑相同)建立實體類User:ide
@Entity(name="t_user") public class User{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String age; //省略getter/setter方法 }
4.建立Repository
分別在org.xiaoyang.dao1包和org.xiaoyang.dao2包(包路徑必定要和JPA配置類中的路徑相同)建立Repository:
UserDao1代碼以下:
ui
public interface UserDao1 extends JpaRepository<User,Integer>{ }
UserDao2代碼以下:url
public interface UserDao2 extends JpaRepository<User,Integer>{ }
5.註解+切面實現兩個數據源事物統一
編寫獲取事務管理器數組的註解:spa
@Target({ ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface MultiDataSourceTransactional { /** * 事務管理器數組 */ String[] transactionManagers(); }
編寫經過註解+切面實現兩個數據源事物統一的配置類:
/** * 註解+切面實現兩個數據源事物統一 */ @Component @Aspect public class MultiDataSourceTransactionAspect { /** * 線程本地變量:爲何使用棧?※爲了達到後進先出的效果※ */ private static final ThreadLocal<Stack<Pair<JpaTransactionManager, TransactionStatus>>> THREAD_LOCAL = new ThreadLocal<>(); /** * 用於獲取事務管理器 */ @Autowired private ApplicationContext applicationContext; /** * 事務聲明 */ private DefaultTransactionDefinition def = new DefaultTransactionDefinition(); { // 非只讀模式 def.setReadOnly(false); // 事務隔離級別:採用數據庫的 def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT); // 事務傳播行爲 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); } /** * 切面 * 路徑必須和編寫獲取事務管理器數組的註解路徑相同 */ @Pointcut("@annotation(org.xiaoyang.anotations.MultiDataSourceTransactional)") public void pointcut() { } /** * 聲明事務 * * @param transactional 註解 */ @Before("pointcut() && @annotation(transactional)") public void before(MultiDataSourceTransactional transactional) { // 根據設置的事務名稱按順序聲明,並放到ThreadLocal裏 String[] transactionManagerNames = transactional.transactionManagers(); Stack<Pair<JpaTransactionManager, TransactionStatus>> pairStack = new Stack<>(); for (String transactionManagerName : transactionManagerNames) { JpaTransactionManager transactionManager = applicationContext.getBean(transactionManagerName, JpaTransactionManager.class); TransactionStatus transactionStatus = transactionManager.getTransaction(def); pairStack.push(new Pair(transactionManager, transactionStatus)); } THREAD_LOCAL.set(pairStack); System.out.println("====pairStack size========"); } /** * 提交事務 */ @AfterReturning("pointcut()") public void afterReturning() { // ※棧頂彈出(後進先出) Stack<Pair<JpaTransactionManager, TransactionStatus>> pairStack = THREAD_LOCAL.get(); while (!pairStack.empty()) { Pair<JpaTransactionManager, TransactionStatus> pair = pairStack.pop(); pair.getKey().commit(pair.getValue()); } THREAD_LOCAL.remove(); } /** * 回滾事務 */ @AfterThrowing(value = "pointcut()") public void afterThrowing() { // ※棧頂彈出(後進先出) Stack<Pair<JpaTransactionManager, TransactionStatus>> pairStack = THREAD_LOCAL.get(); while (!pairStack.empty()) { Pair<JpaTransactionManager, TransactionStatus> pair = pairStack.pop(); pair.getKey().rollback(pair.getValue()); } THREAD_LOCAL.remove(); } }
6.建立Service
經過Service調用Dao層並配置註解實現業務邏輯:
UserService代碼以下:
public interface UserService { //兩個庫同時增長數據 void addUser(User user); //數據庫一增長數據 void addUserOne(User user); //數據庫二增長數據 void addUserTwo(User user); }
UserServiceImpl代碼以下:
@Service public class UserServiceImpl implements UserService { @Autowired private UserDao1 userDao1; @Autowired private UserDao2 userDao2; //同時操做兩個數據庫須要調用自定義註解添加事務組 @Override @MultiDataSourceTransactional(transactionManagers = { "platformTransactionManagerOne","platformTransactionManagerTwo"}) public void addUser(User user) { try { user.setName("小洋同窗"); user.setAge("23"); userDao1.save(user); userDao2.save(user); } catch (Exception e) { e.printStackTrace(); } } //單獨操做數據庫須要標明事務的名稱 @Override @Transactional("platformTransactionManagerOne") public void addUserOne(User user) { try { user.setName("小洋同窗111"); user.setAge("23"); userDao1.save(user); } catch (Exception e) { e.printStackTrace(); } } //單獨操做數據庫須要標明事務的名稱 @Override @Transactional("platformTransactionManagerTwo") public void addUserTwo(User user) { try { user.setName("小洋同窗222"); user.setAge("23"); userDao2.save(user); } catch (Exception e) { e.printStackTrace(); } } }
7.建立Controller
經過Controller調用Service層實現接口功能,代碼以下:
@RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/adduser") public void addUser() { User user= new User(); userService.addUser(user); } @RequestMapping("/adduserone") public void addUserOne() { User user= new User(); userService.addUserOne(user); } @RequestMapping("/addusertwo") public void addUserTwo() { User user= new User(); userService.addUserTwo(user); }