【问题标题】:JPA Delete query not workingJPA删除查询不起作用
【发布时间】:2017-02-25 00:37:31
【问题描述】:

好吧,我不明白为什么我的代码不起作用。有人可以看看。它不提供任何错误消息,但不会删除客户。其他方法运行良好(getCustomerbyId、getAllCustomers 等) 谢谢

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

【问题讨论】:

  • 您使用的是哪个 DBMS?并非所有 DBMS 都支持删除语法
  • 我正在使用 HSQLDB。谢谢。

标签: java sql jpa entitymanager


【解决方案1】:

您需要执行查询才能对数据库产生 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】:

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

    【讨论】:

    • 如果实体具有必须删除的子实体,这将是合适的,否则 OP 的单查询方法更好。
    【解决方案3】:

    您正在创建一个查询,但没有执行它。 你应该添加

    query.executeUpdate();
    

    提交之前

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 2017-08-05
      • 2015-10-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多