0

我在使用 Spring Data Jpa 和 Hibernate 时遇到问题。

这是我得到的例外:

2017-05-21 21:42:20.761 DEBUG 11765 --- [nio-8080-exec-5] o.h.e.t.internal.TransactionImpl         : committing
2017-05-21 21:42:20.765  INFO 11765 --- [nio-8080-exec-5] i.StatisticalLoggingSessionEventListener : Session Metrics {
    14574 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    55978 nanoseconds spent preparing 2 JDBC statements;
    2315850 nanoseconds spent executing 2 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
2017-05-21 21:42:20.779 ERROR 11765 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query] with root cause

javax.persistence.TransactionRequiredException: Executing an update/delete query

当我从 AspectJ 模式更改我的事务管理时

@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)

到默认代理模式:

@EnableTransactionManagement

该异常不再发生。

以下是按调用顺序排列的方法:

来自MessageRestController

@RestController
...
@PatchMapping("mark-messages-as-read/{otherId}")
public void markMessagesAsRead(@CurrentUserAccount UserAccount me, @PathVariable Long otherId) {
    UserAccount other = userAccountService.findUserAccountById(otherId);
    messageService.markMessagesAsRead(me, other);
}

来自MessageService

@Service
@Transactional
...
@Override
public void markMessagesAsRead(UserAccount me, UserAccount other) {
    Assert.notNull(me);
    Assert.notNull(other);
    messageRepository.markMessagesAsRead(me, other);
}

来自MessageRepository

@Modifying
@Query("update Message m set m.messageRead = true where m.recipient = :me and m.sender= :other")
void markMessagesAsRead(@Param("me") UserAccount me, @Param("other") UserAccount other);

我非常想知道为什么从AspectJ-mode 切换到 Proxy-mode 会导致异常不再发生

有人可以建议吗?

编辑:这是服务实现声明:

@Service
@Transactional
public class MessageServiceImpl implements MessageService {

并从服务接口:

void markMessagesAsRead(UserAccount me, UserAccount other);
4

1 回答 1

0

您是否阅读过AspectJ 使用的官方文档?

为此,您必须使用 AspectJ 来编织您的应用程序代码。

当然,使用默认设置它运行良好,因为 Spring AOP 正在为您的类创建运行时代理。

于 2017-05-21T20:42:00.863 回答