gpt4 book ai didi

java - Spring Boot 中的 TransactionRequiredException

转载 作者:行者123 更新时间:2023-12-02 09:28:46 27 4
gpt4 key购买 nike

我的 Controller 如下:

 @GetMapping("/groupByCourse")
public Reply getStudentsCountByCourse(){
Reply reply=new Reply();
reply.setData(service.getStudentsCountByCourse());
return reply;
}

服务是:-

public List getStudentsCountByCourse()  {
List students=new ArrayList<>();

students=studentCourseRepo.findCountStudentByCourse();

getCourseCountByStudent();

return students;
}
@Transactional(Transactional.TxType.REQUIRES_NEW)
public List getCourseCountByStudent() {
List students=new ArrayList<>();

students=studentCourseRepo.findCountCourseByStudent();


return students;
}

存储库是:-

@Repository
public interface StudentCourseRepo extends CrudRepository<StudentCourseTbl, StudentCourseTblPK> {

@Query(value = "select sc.studentCourseTblPK.courseId,count(sc.studentCourseTblPK.studentId) from StudentCourseTbl sc group by sc.studentCourseTblPK.courseId")
List findCountStudentByCourse();

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query(value = "select s.id,s.name,count(sc.studentCourseTblPK.courseId) from StudentCourseTbl sc right join StudentsTbl s on sc.studentCourseTblPK.studentId=s.id group by s.id")
List findCountCourseByStudent();
}

我已经在我的服务方法中使用 @Transactional(Transactional.TxType.REQUIRES_NEW) 来使用 Pessimistic_write 锁执行查询,但即使在事务模式设置为需要新之后,我仍然收到 TransactionRequiredException 。我知道我可以通过在 getStudentsCountByCourse 方法上使用 @Transactional 注释来使代码工作,但我想知道它当前不起作用的原因。

我使用的是springboot版本2.1.7.Release,数据库为mysql

最佳答案

这是 Spring 默认 CGLIB 代理的已知限制。由于事务行为是基于代理的,因此目标对象的一个​​方法调用另一个方法不会导致事务行为,即使后一个方法被标记为事务性的。

可以通过在字节码中编织事务行为而不是使用代理(即使用 AspectJ)来避免这种情况。

您可以在此处阅读有关 Spring 事务管理的更多信息 Method visibility and @Transactional

关于java - Spring Boot 中的 TransactionRequiredException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58138538/

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