2016-10-15 64 views
1

嗯,我不明白爲什麼我的代碼不起作用。有人請看看。它不提供任何錯誤消息,但客戶不會被刪除。其他方法運作良好(getCustomerbyId,getAllCustomers等) 感謝JPA刪除查詢不起作用

public void deleteCustomerById(long id) { 
     EntityManager em = null; 
     try { 
      em = JpaUtil.getFactory().createEntityManager(); 
      em.getTransaction().begin(); 
      Query query = em.createQuery("Delete from Customer c where c.id = :id"); 
      query.setParameter("id", id); 
      em.getTransaction().commit(); 
     } finally { 
      JpaUtil.closeQuietly(em); 
     } 
    } 
+0

您正在使用的數據庫管理系統之前?刪除語法不支持所有DBMS –

+0

我正在使用HSQLDB。謝謝。 –

回答

2

你需要執行查詢有SQL問題的數據庫;在這種情況下,您將需要使用executeUpdate()並獲取修改的行數來驗證是否刪除了某些內容。

 em.getTransaction().begin(); 
     Query query = em.createQuery("Delete from Customer c where c.id = :id"); 
     query.setParameter("id", id); 
     int rows = query.executeUpdate(); 
     em.getTransaction().commit(); 
2

您正在創建查詢但未執行查詢。 您應該添加

query.executeUpdate(); 

0

使用JPA的API查找(Customer.class)找到客戶對象,然後使用移去那些所謂(對象)

+0

如果實體的子實體也必須被刪除,那將是適當的,否則OP的單一查詢方法更好。 – coladict