Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

java - How to delete by criteria in 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;
}
question from:https://stackoverflow.com/questions/8958217/how-to-delete-by-criteria-in-hibernate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...