我试图删除数据库中超过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(时间戳)之后,记录仍然存在于DB中;被称为。(因为那一行出现了错误,但由于糟糕的日志,我不知道哪里出错了。)
我检查了SpringDocumentation,似乎我得到了一切正确的..
使用Spring包中的@Transactional注释像@org.springframework.transaction.annotation.Transactional