如何使我的实体对象受到管理,以便可以将其删除? [英] How do I make my entity object managed so I can remove it?

查看:59
本文介绍了如何使我的实体对象受到管理,以便可以将其删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用-我总是会抛出IllegalArgumentException并提出尝试合并分离的对象,然后再次尝试删除"的建议.

This doesn't work -- I always get the IllegalArgumentException thrown with the advice to "try merging the detached and try the remove again."

@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);
    }
}

输出日志显示以下内容:

The output log shows the following:

INFO: delete() entity not managed: com.database.SomeTable[ id=2 ]  
INFO: delete() this entity should now be managed: false

换句话说, merge()不返回托管实体.谁能发现我做错了什么?

In other words the merge() does not return a managed entity. Can anyone spot what I did wrong?

第二个问题:有没有办法在一次交易中而不是在两次交易中做到这一点?

Second question: is there a way to do this in one transaction rather than two?

这是GlassFish 3.1中的EclipseLink.

This is with EclipseLink inside GlassFish 3.1.

推荐答案

提交后,您的持久化上下文应该消失了.因此,提交后的println测试将失败,因为不再管理目标"对象.

After commiting your persistence context should be gone. So your println test after the commit will fail, because the "target" object is not managed anymore.

在一次交易中完成所有工作,它应该可以工作.您只需在尝试"开始后就开始交易.

Do all your stuff within one transaction and it should work. You just have to start your transaction after your "try" begins.

这篇关于如何使我的实体对象受到管理,以便可以将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆