JPA Delete query not working
13,952
Solution 1
You need to execute queries to have SQL issues to the database; in this case you will want to use executeUpdate() and get the modified row count to verify something was deleted or not.
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();
Solution 2
You are creating a query but not executing it. You should add
query.executeUpdate();
before committing
Author by
Aare Aasmäe
Updated on June 17, 2022Comments
-
Aare Aasmäe almost 2 years
Well, I do not understand why me code does not work. Could Someone please take a look. It does not provide any error messages but the Customer will not be deleted. Other methods are working well (getCustomerbyId, getAllCustomers and so) Thanks
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); } }
-
coladict over 7 yearsThat would be appropriate if the entity has child-entities that must also be deleted, otherwise OP's one-query approach is better.