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

标签 java hibernate jpa transactions

我有一个标有 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/

相关文章:

JPA : What is the behaviour of merge with lazy initialized collection?

java - Hibernate + Spring = Java Web 应用程序的最先进技术?

java - Hibernate AUTO 刷新策略顺序

java - 如何在Android中创建一个简单的视频播放器?

java - 为什么 Java 8 Instant.now() 在我的本地服务器上显示错误的 UTC?

java - Hibernate 中的多对多关系不返回结果

java - JSF/JPA - 多个复选框

java - Spring Boot 无法提取 ResultSet

java - 沿着 LibGDX 中的路径 vector 偏移 Sprite

java - Selenium Java - 我如何只运行一个测试?