0

I want to delete list of record from my table using hibernate:

My sql query would look like:

delete from students where joinDate="2014-03-08"

I would like to delete all the record who joined in above mentioned date.

In students table, I'm having two foreign keys: classId and courseId.

Can you help how to write effective way of hibernate delete query for above scenario?

Appreciate your help!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

1

The simplest way would be to delete from each table individually:

-- Remove all connections from A which reference
-- the B-rows you want to remove
DELETE FROM A_has_B
WHERE B_id IN (1,2);

-- Remove all connections from C which reference
-- the B-rows you want to remove
DELETE FROM C_has_B
WHERE B_id IN (1,2);

-- Finally remove the B-rows
DELETE FROM B
WHERE B_id IN (1,2);
Parth Akbari
  • 641
  • 7
  • 24
1

You can delete multiple records by using HQL as below:

Transaction transaction = session.beginTransaction();
try {
  // your code
  String hql = "delete from students where joinDate= :joinDate";
  Query query = session.createQuery(hql);
  System.out.println(user.getUid() + " and pid: " + pid);
  query.setDate("joinDate", student.getJoinDate());
  System.out.println(query.executeUpdate());
  // your code end

  transaction.commit();
} catch (Throwable t) {
  transaction.rollback();
  throw t;
}

Apart from this you can use session.delete(student); method to delete the record

0

Try this . Refer

Hibernate HQL delete with and

      String deleteQuery = "delete from students where joinDate= :joinDate";
      Query query = session.createQuery(deleteQuery);
      query.setString("joinDate", "2014-03-08"); //convert date from string
      query.executeUpdate()

Pass join date in the query correctly. I assume join date datatype is string . If join date data type is date convert date string to java.util.date using SimpleDateFormat then pass parameter . string to date conversion

Community
  • 1
  • 1
Ramesh
  • 1,872
  • 2
  • 20
  • 33