I have a student table and want to delete all students in a class.
So my sql query would look like:
delete from student where classId = 333
How can I do this using hibernate with criteria?
I need this so I can put in one of my base classes to use by any DAO objects that extend from it. So I can make this generic across all of my DAO objects.
Currently I have created a generic method that will taken in the Student Object - calls the find method that uses the criteria to get the list and then I do a batch delete under one transaction as follows:
public boolean deleteByCriteria(Object deleteObject) {
List deleteObjectList = find(deleteObject);
if (deleteObjectList == null)
return false;
return deleteAll(deleteObjectList);
}
public boolean deleteAll(List deleteObjectList) {
if (logger.isDebugEnabled()) {
logger.debug("Entered BaseSchoolRollBookDAO -> delete");
logger.debug("Object for batch deletion [" + deleteObjectList + "]");
}
boolean result = false;
Transaction tx = null;
// Get CurrentSession from HibernateUtils
Session session = HibernateUtils.getSession();
// Start transaction
tx = session.beginTransaction();
// Create new Criteria to be passed
try {
int flushCount = 0;
for (Object deleteObject : deleteObjectList) {
session.delete(deleteObject);
flushCount++;
if (flushCount % 20 == 0) {
session.flush();
session.clear();
}
}
tx.commit();
result = true;
} catch (HibernateException e) {
logger.fatal("Exception in executing batch Delete query", e);
if (tx != null && tx.isActive())
tx.rollback();
}
return result;
}
question from:https://stackoverflow.com/questions/8958217/how-to-delete-by-criteria-in-hibernate