I'm trying to delete all records from my database that are older than 2 days but I keep getting this not-so-useful error so I don't know what to do:
Some problem occured: org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
My code looks like this:
In one class I'm calling testService's deleteOldRecords method:
// 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);
This is the implementation of that method:
@Override
public void deleteOldRecords(long timestamp) {
testDao.deleteOldRecordsCRUD(timestamp);
}
Now I'm trying to call deleteOldRecordsCRUD which is a custom query. Here's the method:
@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);
}
I have table created, with some records in it but this is not working, that is, records still exist in DB after testDao.deleteOldRecordsCRUD(timestamp); is called. (Because of the error that appears on that line, but due to poor log, I don't know what went wrong.)
I checked SpringDocumentation and it seems that I got everything right..
CodePudding user response:
Use the @Transactional annotation from Spring package
like @org.springframework.transaction.annotation.Transactional
At method level.