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.
- 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();
}
- 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.
- 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?