Hello all,
How to limit records to be deleted with jpa delete query by rownumber because setFirstResult() doesn't work with delete (named) query?
Problem:
When is history entry written into table, I want always to keep last <n> records in table (delete older records from n+1 to maxRecords).
THIS DOESN'T WORK (all records are deleted regardless setFirstResult() ):
Code:
/* @NamedQuery(name = "history.delete",
query = "DELETE FROM History hist WHERE hist.username = :username ORDER BY hist.timestamp DESC") */
Query queryDelHistory = em.createNamedQuery("history.delete");
queryDelHistory.setParameter("username", username);
queryDelHistory.setFirstResult(n);
int deletedRecords = queryDelHistory.executeUpdate();
THIS WORKS (correct records deleted one by one, not very effiicient):
Code:
/* @NamedQuery(name = "history.read",
query = "SELECT hist FROM History hist WHERE hist.username = :username ORDER BY hist.timestamp DESC")*/
Query queryReadHistory = em.createNamedQuery("history.read");
queryReadHistory.setParameter("username", username);
queryReadHistory.setFirstResult(n);
List<History> historyList= queryReadHistory.getResultList();
for (History history:historyList ) {
em.remove(history);
}
My dependencies:
Hibernate: 3.3.2 GA, Annotations 3.4.0 GA, EntityManager 3.4.0 GA
MySQL Community 5.1.43
Many thanks in advance,
Boris