Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete by criteria in hibernate?

Tags:

java

hibernate

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; } 
like image 709
chan Avatar asked Jan 22 '12 01:01

chan


People also ask

How do I delete a record in Hibernate?

Hibernate: delete from PRODUCT where price>? Query query = session. createQuery( "delete Category where id = :ID" );

How can I delete multiple rows in Hibernate?

In a non-transactional environment, multiple rows can be deleted in a batch in Hibernate something like the following. Session session=HibernateUtils. getSessionFactory(). getCurrentSession(); session.

How do you update using criteria Hibernate?

Session session = sessionFactory. openSession(); Transaction tx = session. beginTransaction(); String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName"; // or String hqlUpdate = "update Customer set name = :newName where name = :oldName"; int updatedEntities = s. createQuery( hqlUpdate ) .

What is remove method in Hibernate?

In Hibernate, an entity can be removed from a database by calling the Session#delete() or Session#remove() . Using these methods, we can remove a transient or persistent object from datastore. The following examples demonstrate the use of Session#delete() and Session#remove() methods.


2 Answers

For deleting use HQL which is the best option, I think, Criteria's main purpose is for only retrieving the data.
This one is with Criteria

  Student student = (Student ) session.createCriteria(Student.class)                     .add(Restrictions.eq("classId", classId)).uniqueResult();   session.delete(student); 

And this one is simple HQL query:

String hql = "delete from Student where classId= :classId"; session.createQuery(hql).setString("classId", classId).executeUpdate(); 
like image 116
Jama A. Avatar answered Sep 23 '22 20:09

Jama A.


You can easily achieve by following simple hibernate as follows,

Session session=getSession();   String hql = "delete from Student where classId= :id";  session.createQuery(hql).setLong("id", new Integer(id)).executeUpdate(); 

for details refer

like image 36
Shams Avatar answered Sep 22 '22 20:09

Shams