简体   繁体   English

JPA EntityManager不删除实体

[英]JPA EntityManager not removing entities

I want to delete a list of entities from database. 我想从数据库中删除实体列表。 List<LetterEntity> letterToDel - the list of entities. List<LetterEntity> letterToDel - 实体列表。 I tried to remove this list in many ways. 我试图以多种方式删除此列表。

  1. I create one transaction and delete each entity in loop 我创建一个事务并在循环中删除每个实体
    EntityTransaction trx = em.getTransaction();
    try {

      for (LetterEntity l : lettersToDel) {
         trx.begin();
         em.remove(l);
         em.flush();
         trx.commit();
      } 

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
         if (trx.isActive())
             trx.rollback();
     }
  1. I create new transaction for every deleting in loop 我为每个循环删除创建新事务

    try {

      for (LetterEntity l : lettersToDel) {
         EntityTransaction trx = em.getTransaction();
         trx.begin();
         em.remove(l);
         em.flush();
         trx.commit();
      } 

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
         if (trx.isActive())
             trx.rollback();
    }

In case 1,2 there is no exceptions, but entities not deleting. 在案例1,2中没有例外,但实体没有删除。

  1. I tried to delete entities with query 我试图用查询删除实体

    try {
      for (LetterEntity l : lettersToDel) {
              em.createQuery("delete  from LetterEntity l where l = :letter")
                 .setParameter("letter", l)
                 .executeUpdate();
      }
    } catch (Exception e) {
        e.printStackTrace();
    }

In case 3 there is an exception: 在案例3中有一个例外:

javax.persistence.TransactionRequiredException: Executing an update/delete query

What I'm doing wrong? 我做错了什么?

The code should create a transaction prior to executing the query. 代码应该在执行查询之前创建事务。

try {
     EntityTransaction trx = em.getTransaction();
     trx.begin();   
      for (LetterEntity l : lettersToDel) {
              em.createQuery("delete  from LetterEntity l where l = :letter")
                 .setParameter("letter", l)
                 .executeUpdate();
     trx.commit();
      }
    } catch (Exception e) {
        e.printStackTrace();
    }

For case 3, this is normal. 对于案例3,这是正常的。 You need a transaction to perform an update. 您需要一个事务来执行更新。 (If you use Spring, simply add @Transactional annotation to the method) (如果使用Spring,只需在方法中添加@Transactional注释)

For 1 and 2, do you go in trx.rollback(); 对于1和2,你进入trx.rollback(); in your finally statement ? 在你的最后陈述?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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