为什么即使表是空的,Hibernate的DELETE也会返回1?

时间:2014-03-12 14:39:42

标签: java mysql sql hibernate

我有一段非常简单的代码,目的是只删除1条记录(如果存在!):

public String deleteOneRecord(String recordUniqId) { 
  // System.out.println(recordUniqId);
  try {
    String _return =  "recordId " + recordUniqId + " not found.";

    Session session = HibernateUtil.getSessionFactory().openSession(); // commit closes it
    session.beginTransaction(); 
    String hql = "delete from MyTable where record_id= :recordUniqId"; 
    int numDeleted = session.createQuery(hql).setString("recordUniqId", recordUniqId).executeUpdate();          
    if (numDeleted == 1); {
      _return = "Successfully deleted recordId " + recordUniqId;
    }
    session.getTransaction().commit();

    return _return;
  } 
  catch (Exception ex) {
    ex.printStackTrace();
    throw new RuntimeException(ex);
  }
}

此代码删除由Id指定的记录(并返回1),但即使表为空,它也会返回1。

为什么?

Isn&#t; t Query.executeUpdate()是否应该返回更新或删除的实体数量?

1 个答案:

答案 0 :(得分:6)

它没有返回1。问题是,在你的if陈述之后,你有一个悬空的分号:

if (numDeleted == 1);   // <-- Here

这使得下面的代码块只是一个独立的本地块,无论如何都会执行。