我使用Spring Data Jpa&冬眠。
以下是我得到的例外情况:
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模式切换到代理模式会导致异常不再发生。
有人可以提出建议吗?
编辑:这是服务实现声明:
@Service
@Transactional
public class MessageServiceImpl implements MessageService {
并从服务界面:
void markMessagesAsRead(UserAccount me, UserAccount other);
答案 0 :(得分:0)
您是否阅读过使用AspectJ的官方documentation?
您必须使用AspectJ来编织应用程序代码。
当然,使用默认设置,它可以很好地工作,因为Spring AOP正在为您的类创建运行时代理。