I am developping a Hibernate / Spring application with a built-in database maintenance feature. Every 15 minutes it looks at certain tables and will purge old records based on certain parameters. In the case of my LogEntry entity for example, i am purging based on 2 parameters : how old the record is and how many records are in the table. In the first case, I am doing something like this :
@Override
public int deleteExpiredEntries(int systemLogKeepTimeInDays, int systemLogMaxEntries)
{
Session session = getSession();
Query query = session.createQuery("DELETE FROM LogEntry l WHERE l.time < :p");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -systemLogKeepTimeInDays);
return query.setParameter("p", cal.getTime()).executeUpdate();
}
How can I keep say 5000 records when this maintenance runs using a similar process?
I thought of using the Id column and purging whatever has a greater Id than 5000 but this would actually purge the new records and not the old ones!
How would you approach this problem?