我有一个 CrudRepository 和一个删除数据的方法:
public interface SampleRepository extends PagingAndSortingRepository<Sample, String> {
@Modifying
@Transactional
@Query("delete from Sample where creationTimestamp <= ?1")
public void deleteOutdatedData(Instant expirationTimestamp);
}
如果我使用休息 Controller ,它就可以工作:
@RequestMapping(value = "/delele", method = RequestMethod.DELETE)
public void deleteOldData(@RequestParam(value = "date") String date) {
sampleRepository.deleteOutdatedData(Instant.parse(date));
}
我想实现一个调度程序来删除过时的数据。 例如:
@Scheduled(fixedDelayString = "${clean-processing-delay}")
public void cleanOutdatedData() {
Instant instant = Instant.now().minusMillis(expirationInterval);
sampleRepository.deleteOutdatedData(instant);
}
调度程序在正确的时间工作,但我发现了一个异常:
nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
我哪里错了?
最佳答案
您需要将您的方法封装在事务中,如下所示:
@Scheduled(fixedDelayString = "${clean-processing-delay}")
@Transactional
public void cleanOutdatedData() {
Instant instant = Instant.now().minusMillis(expirationInterval);
sampleRepository.deleteOutdatedData(instant);
}
关于java - 调度程序、CrudRepository 和 TransactionRequiredException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057589/