0

I want to delete a list of entities from database. List<LetterEntity> letterToDel - the list of entities. 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. 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:

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

What I'm doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mary Ryllo
  • 2,321
  • 7
  • 34
  • 53

2 Answers2

2

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();
    }
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

For case 3, this is normal. You need a transaction to perform an update. (If you use Spring, simply add @Transactional annotation to the method)

For 1 and 2, do you go in trx.rollback(); in your finally statement ?

Samuel EUSTACHI
  • 3,116
  • 19
  • 24
  • No, it's not going in finally block, I don't know why. The solution below is working, but why deleting with EntityManager not working? – Mary Ryllo Feb 20 '13 at 10:25