获取在同一事务中使用@Transactional 插入的数据

Get the data which is inserted using @Transactional in the same transaction

我在一种方法(具有 @Transactional(propagation = Propagation.Required))中插入数据,但在另一种方法(具有 @Transactional(propagation = Propagation.Required))中插入数据,如果我尝试获取相同的数据,它会给出空值。

这两个方法都写在服务层用@Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)

如何获取同一事务中插入的数据。 像 :-

 @Service
    public class Service{
        @Transactional
        public void method(){
            mapper.insert();        //insert to DB(Using Mapper interface)
            ServiceLayer.method2()
        }
    }

@Service
public void ServiceLayer{

    @Transactional
    public static void method2(){
        result  = mapper.select() //Select inserted data - returning null
    }
}

为了保留对当前会话所做的更改,您可以调用 entityManager.flush();

我找到了答案...从 ServiceLayer.method2() 中删除 @transactional 后它工作正常。

它可能有效,但不是解决方案。 在您的情况下,您的 Transaction 来自 Service.method() 创建了一个尚未提交的事务。这就是你无法获取它的原因。