I'm looking for an eloquent way to delete multiple entities inside a transaction.
Given a list of ids, I would like to throw an exception if the count of affected rows differs from the list count. Currently I use the below snippet, but it involves a lot of boilerplate:
private int deleteMyEntities(final List<Integer> ids) {
final Session session = SomeHelper.getOpenSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
final int affectedCount = session.createQuery("delete MyEntity where id in (:ids)")
.setParameterList("ids", ids)
.executeUpdate();
if (affectedCount == ids.size()) {
tx.commit();
tx = null;
return affectedCount;
} else {
throw new HibernateException("Delete count does not match target count.");
}
} finally {
if (tx != null) {
tx.rollback();
}
}
}
Some gotchas:
- This is a legacy app lacking dependency injection, annotation driven transactions and other niceties. Answers akin to "Use spring" aren't exceptionally helpful.
- We compile to java 1.6.