删除所有早于 2 天的记录 SpringData/自定义查询
Delete all records older than 2 days SpringData / custom query
我试图从我的数据库中删除超过 2 天的所有记录,但我一直收到这个不太有用的错误,所以我不知道该怎么做:
Some problem occured: org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
我的代码如下所示:
其中一个 class 我正在调用 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);
}
我创建了 table,其中有一些记录,但这不起作用,也就是说,在 testDao.deleteOldRecordsCRUD(timestamp) 之后,记录仍然存在于数据库中;叫做。 (因为那一行出现的错误,但是由于log不好,不知道哪里出了问题。)
我检查了 SpringDocumentation,似乎我做对了一切..
使用来自 Spring 包的@Transactional 注释
喜欢 @org.springframework.transaction.annotation.Transactional
在方法级别。
我试图从我的数据库中删除超过 2 天的所有记录,但我一直收到这个不太有用的错误,所以我不知道该怎么做:
Some problem occured: org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
我的代码如下所示:
其中一个 class 我正在调用 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);
}
我创建了 table,其中有一些记录,但这不起作用,也就是说,在 testDao.deleteOldRecordsCRUD(timestamp) 之后,记录仍然存在于数据库中;叫做。 (因为那一行出现的错误,但是由于log不好,不知道哪里出了问题。)
我检查了 SpringDocumentation,似乎我做对了一切..
使用来自 Spring 包的@Transactional 注释
喜欢 @org.springframework.transaction.annotation.Transactional
在方法级别。