交易结束时 JPA 隐式刷新未发生
JPA implicit flush at end of transaction not happening
我有一个标有 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 个用户在数据库中获取日期,而第三个用户永远不会刷新到数据库并保持无日期。
所以我的理解似乎是错误的。我错过了什么?
问题是您的方法是私有的,默认情况下 Spring 只能在从另一个 class 调用的 public 方法中启动事务。您可以使用 aspectJ 来解决这个问题。
来自springdocs
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.
我有一个标有 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 个用户在数据库中获取日期,而第三个用户永远不会刷新到数据库并保持无日期。 所以我的理解似乎是错误的。我错过了什么?
问题是您的方法是私有的,默认情况下 Spring 只能在从另一个 class 调用的 public 方法中启动事务。您可以使用 aspectJ 来解决这个问题。
来自springdocs
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.