如何使用hibernate java中的where条件删除多条记录

时间:2015-04-09 04:50:33

标签: java hibernate

我想使用hibernate从表中删除记录列表:

我的SQL查询看起来像:

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

我想删除在上述日期加入的所有记录。

在学生表中,我有两个外键:classId和courseId。

您能否帮助如何为上述场景编写有效的hibernate删除查询方式?

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

最简单的方法是从每个表中单独删除:

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

答案 1 :(得分:0)

您可以使用HQL删除多条记录,如下所示:

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;
}

除此之外,您可以使用session.delete(student);方法删除记录

答案 2 :(得分:0)

试试这个。 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()

正确地在查询中传递加入日期。我假设join date数据类型是字符串。如果使用SimpleDateFormat将日期转换日期字符串连接到java.util.date,则传递参数。 string to date conversion

相关问题