简体   繁体   中英

JPA Delete query not working

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

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

You are creating a query but not executing it. You should add

query.executeUpdate();

before committing

使用 jpa APIs find(Customer.class) 找到客户对象然后使用 romove(object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM