首页 > 解决方案 > Spring JPA Transaction 问题,未保存实例

问题描述

我遇到了 sping JPA @Transaction 的问题(我认为),下面是最少的代码:

    //package 1
    @Transactional
    public void method_m1(){
        Result result = method_m2();
        audit(result);
    }
    
    //package 2
     @Transactional(propagation = Propagation.REQUIRED)
    public Result method_m2(){
    
      Result result = new Result()  
      //creating object say User(User mapped to database table users)
      User u = new User();
      // setting some attributes;
      
      u = userRespositoy.save(user);
      // tried with saveAndFlush no luck
      result.set(u);
      return result ;
    }
    
    //package 3
   @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void audit(Result result){
       CompletableFuture.runAsync(
            () -> {
            //auditing user saving to db
            User user = userRepository.findById(result.get().getId()).orElseThrow(() -> new 
            UserNotFoundException("user not found, userId :" + result.get().getId()));
        });
    }

在从数据库获取异常的 userId 获取新创建的用户时。

谁能解释一下这里发生了什么?

提前赞赏。

标签: javaspringhibernatespring-data-jpa

解决方案


推荐阅读