I want to implement deleteAll
method that will be delete all User
entities with their associations, at the same time I want to prevent java.lang.OutOfMemoryError
exception when fetching users collection in memory heap.
My current implementation looks like the code snippet below:
public void deleteAll() {
final int PAGE_SIZE = 15;
final int PAGE_NUMBER = 0;
final String SORTING_PROPERTY_NAME = "id";
List<User> result;
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(User.class);
criteria.addOrder(Order.asc(SORTING_PROPERTY_NAME));
criteria.setFirstResult(PAGE_NUMBER);
criteria.setMaxResults(PAGE_SIZE);
do {
result = criteria.list();
result.forEach(session::delete);
} while (result.size() == PAGE_SIZE);
}
As you see I am using pagination approach so I fetched one bulk of data then delete it and so on. How this is achieved in reality with Hibernate? Thank you for help.