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