如何删除detached instance?

来源:互联网 发布:linux 安装oracle9i 编辑:程序博客网 时间:2024/06/05 14:48

      昨天在做EJB底层DAO的开发时,抱着试试心态传了一个Object进去(之前一直是传Id,然后在删除之前find对象),谁知用Junit测试时竟报出这个异常:

 

      java.lang.IllegalArgumentException: Removing a detached instance

      意思就是说在删除一个detached instance(已分离)对象时出错

 

      之前出错代码:

 

      @PersistenceContext

       private EntityManager entityManager;
       
       
       public void delete(SASVo  vo) {
               entityManager.remove(vo);
        }

       这段代码看上去似乎没有任何问题,但执行就出错,之后查阅相关资料关于Detached,是这么说:

      Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the

      object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be

      reattached to a new Session at a later point in time, making it (and all the modifications) persistent again

      现在应该明白了吧,在删除之前把这个Detached instance绑定到当前的Sesssion,在用当前Sesssion删除此instance。修改后的代码如

      下:

       @PersistenceContext

       private EntityManager entityManager;
       
       
       public void delete(SASVo  vo) {
               entityManager.remove( entityManager.merge(vo));
        }

 

 

原创粉丝点击