我试图从我的数据库中删除超过2天的所有记录,但我一直收到这个不太有用的错误,所以我不知道该怎么办:
Some problem occured: org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query我的代码如下所示:
在一个类中,我调用了testService的deleteOldRecords方法:
// Delete records older than two days (takes current time and then removes 2 days from today's date (172 800 000 ms = 2 days)
testService.deleteOldRecords((ZonedDateTime.now().toInstant().toEpochMilli())-172_800_000);下面是该方法的实现:
@Override
public void deleteOldRecords(long timestamp) {
testDao.deleteOldRecordsCRUD(timestamp);
}现在,我尝试调用deleteOldRecordsCRUD,这是一个自定义查询。下面是方法:
@Repository
public interface TestItemDAO extends CrudRepository<TestItem, Long> {
//This will delete records older then two days!
@Modifying
@Query(value = "DELETE FROM TEST_TABLE tt WHERE tt.timestamp <= :timestamp", nativeQuery = true)
void deleteOldRecordsCRUD(@Param("timestamp") long timestamp);
}我已经创建了表,其中有一些记录,但这不起作用,也就是说,在调用testDao.deleteOldRecordsCRUD(时间戳);之后,记录仍然存在于数据库中。(由于该行上显示的错误,但由于日志不佳,我不知道哪里出了问题。)
我检查了SpringDocumentation,似乎一切都是正确的..
发布于 2021-10-01 10:50:45
在方法级别使用来自Spring包的@Transactional注解,如@org.springframework.transaction.annotation.Transactional。
https://stackoverflow.com/questions/69404595
复制相似问题