gpt4 book ai didi

java - 事务结束时 JPA 隐式刷新未发生

转载 作者:行者123 更新时间:2023-12-01 11:14:43 25 4
gpt4 key购买 nike

我有一个标有 org.springframework.transaction.annotation.Transactional 的方法

@Transactional
private void bob(String userName){
User user = userRepo.getUser(userName);//autowired repo finds User domain Object
user.setSomeDate(new Date());
}

然后我在循环中调用这个方法

for(String userName: userNames ){
System.outPrintln("something happens before we cal it again.");
bob(userName);
}

存储库找到用户并且没有记录任何异常。

我的理解是脏用户对象是一个托管实体,并且会在事务退出时保存。

我实际看到的是,当事务方法 bob 被租用时,用户会被刷新。因此,如果 for 循环在执行后有 3 个用户名,我可以看到前 2 个用户在数据库中获取日期,而第三个用户永远不会刷新到数据库并保持无日期状态。所以我的理解似乎是错误的。我缺少什么?

最佳答案

问题是你的方法是私有(private)的,默认情况下Spring只能在从另一个类调用的公共(public)方法中启动事务。您可以使用aspectJ 来解决这个问题。

来自 Spring docs

Method visibility and @Transactional

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

关于java - 事务结束时 JPA 隐式刷新未发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31973957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com