JPA多源数据库配置(达梦数据库)

。_饼干妹妹 提交于 2020-11-02 13:01:53


本篇文章主要介绍SpringBoot框架实现Jpa多源数据库的配置,本次使用国产数据库达梦数据库做为数据源。

1.准备工作

在pom.xml文件中引入Spring Data Jpa依赖:

 <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配置:

@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:

@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代码如下:

public interface UserDao1 extends JpaRepository<User,Integer>{
   
    }

UserDao2代码如下:

public interface UserDao2 extends JpaRepository<User,Integer>{
   
    }

5.注解+切面实现两个数据源事物统一

编写获取事务管理器数组的注解:

@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);
    }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!