0

Can I use Criteria to delete records from my tables?

For example,

Criteria toDelete = session.createCriteria(Car.class, "car").createAlias("car.wheel", "wheel");
toDelete.add(Restrictions.eq("brand", "Toyota"));
toDelete.add(Restrictions.eq("wheel.brand", "BBS");
toDelete.add(Restrictions.gt("date_of_purchase", someDay);
toDelete.add(Restrictions.between("cost", 3000, 5000);

How can I use toDelete criteria to delete the records that I am interested in? An inefficient way would be to query for the ids using the toDelete criteria, then delete Car objects from there. Also, can I know how many objects have I deleted?

2 Answers 2

2

You should upgrade your hibernate version to a version that implements JPA 2.1 (Hibernate starts JPA 2.1 on version 4.3.11.Final - Hibernate Downloads)

Once you have upgraded, you can use CriteriaDelete to do what you want. here is a small example: Example

Sign up to request clarification or add additional context in comments.

Comments

1

In my opinion, you cannot do that because Hibernate does not support. As a replacement, you can use something like:

String hql = "delete from User where UserName = :name";
Query query = session.createQuery(hql);
query.setString("name", "User 9");
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);

Best regards, Hung NGUYEN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.