【发布时间】:2011-09-16 17:35:14
【问题描述】:
这不起作用——我总是抛出 IllegalArgumentException 并建议“尝试合并分离的并再次尝试删除”。
@PersistenceContext private EntityManager em;
@Resource private UserTransaction utx;
public void delete(EN entity) {
if (entity == null) return; // null-safe
EN target = entity;
try {
if (!em.contains(entity)) {
System.out.println("delete() entity not managed: " + entity);
utx.begin();
target = em.merge(entity);
utx.commit();
System.out.print("delete() this entity should now be managed: " + em.contains(target));
}
utx.begin();
em.remove(target);
utx.commit();
} catch (RollbackException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (HeuristicMixedException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (HeuristicRollbackException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IllegalStateException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (NotSupportedException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (SystemException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
输出日志显示如下:
INFO: delete() entity not managed: com.database.SomeTable[ id=2 ]
INFO: delete() this entity should now be managed: false
换句话说,merge() 不返回托管实体。谁能发现我做错了什么?
第二个问题:有没有办法在一次交易而不是两次交易中做到这一点?
这是 GlassFish 3.1 中的 EclipseLink。
【问题讨论】:
-
您是否尝试过在事务中而不是在外部进行合并?