【发布时间】:2016-11-01 21:35:09
【问题描述】:
我正在寻找一种雄辩的方式来删除事务中的多个实体。
给定一个 id 列表,如果受影响的行数与列表数不同,我想抛出一个异常。目前我使用下面的sn-p,但它涉及到很多样板:
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();
}
}
}
一些陷阱:
- 这是一个缺乏依赖注入、注释驱动事务和其他细节的遗留应用程序。类似于“使用弹簧”的答案并不是特别有帮助。
- 我们编译成 java 1.6。
【问题讨论】:
-
这段代码有什么问题?
-
有大量的样板。它有效,只是丑陋
-
代替 MyEntity 对象创建一个只有 id 字段的 DTO