`
lw223
  • 浏览: 99451 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

如何删除detached instance?

    博客分类:
  • java
阅读更多

http://blog.csdn.net/MyJSF/archive/2007/12/01/1910491.aspx

应用实例环境:Spring jpa hibernate3
常用数据库表的删除办法,一般都会在DAO类中提供delete.如下例:
public class UnitDAO implements IUnitDAO {
        private EntityManager entityManager;
       
        @PersistenceContext
        public void setEntityManager(EntityManager entityManager) {
                this.entityManager = entityManager;
        }
       
        private EntityManager getEntityManager() {
                return this.entityManager;
        }
       
        public void delete(Unit persistentInstance) {
                try {
                        getEntityManager().remove(persistentInstance);
                } catch (RuntimeException re) {
                        throw re;
                }
        }

        public List<Unit> findAll() {
                try {
                        String queryString = "select model from Unit model";
                        return getEntityManager().createQuery(queryString).getResultList();
                } catch (RuntimeException re) {
                        throw re;
                }
        }
}
看上去,没有任何问题,这也是在MyEclipse中自动产生的代码。但是,在实际运行过程中,界面会调用findAll()获得全部的unit记录显示在界面层,根据业务需求,用户选择一个unit进行删除,当调用delete方法时,出现异常:
        java.lang.IllegalArgumentException: Removing a detached instance com.gotop.rbac.model.Unit#1
   意思就是说,在删除一个detached instance出错。

  •     解决办法:

看看Hibernate是如何处理对象的.Chapter 10. Working with objects. http://www.hibernate.org/hib_docs/reference/en/html/objectstate.html
    说的很清楚。Hibernate object states有三种状态:Transient、Persistent、Detached。关于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是一个已经持久化的对象,但是它的Session已经关闭了,它的引用依然有效,当然,detached instance可能被修改。detached instance能够在以后可以重新附属到一个新的Session,使之能重新序列化。
   
        好了,找到解决办法了,在删除之前把这个Detached instance绑定到当前的Sesssion,在用当前Sesssion删除此instance。getEntityManager()提供merge方法实现。
修改后的delete代码:
        public void delete(Unit persistentInstance) {
                try {
                        getEntityManager().remove(getEntityManager().merge(persistentInstance));
                } catch (RuntimeException re) {
                        throw re;
                }
        }
       千万不要写成:
        try {
                getEntityManager().merge(persistentInstance);
                getEntityManager().remove(persistentInstance);
        }              
       执行完merge后persistentInstance还是detached, merge后返回的新对象才是允许删除的。  

分享到:
评论
1 楼 iStar 2010-09-23  
Goooood!

相关推荐

    subl-mac:Mac的Sublime Text配置

    Mac的Sublime Text配置这是我的Mac版Sublime Text 3配置。 添加Vim行为的显着变化: 复古(Vim)已开启Vim边栏导航Vim“ jj”用于退出编辑模式Vim“ alt-j”和“ alt-k”用于上一页和下一页使用剪贴板进行Vim剪切/...

    AWS certified solutions architect associate exam sample

    - **Option D**: The ENI (Elastic Network Interface) is not detached when an instance is stopped and started. ENIs remain associated with the instance even during stop/start operations. - **Option E*...

    jsPlumb连线实例

    console.log("Connection between ", connection.sourceId, " and ", connection.targetId, " was detached."); }); ``` 此外,还可以利用jsPlumb的API进行其他操作,如添加新的端点、批量连接、批量删除连接等。...

    Hibernate Reference Documentation3.1

    2.2. Instance states 2.3. JMX Integration 2.4. JCA Support 2.5. Contextual Sessions 3. Configuration 3.1. Programmatic configuration 3.2. Obtaining a SessionFactory 3.3. JDBC connections 3.4. Optional...

    JPA 开发中遇到的错误

    org.hibernate.TransientObjectException: object references an unsaved transient instance 当一个实体引用了另一个尚未保存的实体时,会抛出此类异常。这通常发生在级联保存的场景中,如果父实体尝试保存时,子...

    hibernate 经典题目 其中包括很多核心的题目

    ORM 的基本原则是:类(Class)映射到表(Table),属性(Property)映射到列(Column),关联关系(Association)映射到外键(ForeignKey),类型实例或对象(Instance/Object)映射到行(Row)。 2. Hibernate ...

    j2ee攻略(经典)

    **2.2 实例池化 (Instance Pooling)** EJB容器通过实例池化来优化无状态会话Bean的性能。当客户端请求Bean时,容器会从池中选择一个可用实例。 **2.3 Stateless Session Bean的生命周期** 无状态会话Bean的生命...

    Git-2.21.0-64-bit.zip

    instance throughout more codepaths. * When one step in multi step cherry-pick or revert is reset or committed, the command line prompt script failed to notice the current status, which has been ...

    hibernate_reference.pdf

    - **Instance States**: Details about the various states an entity can be in (e.g., transient, persistent, detached) and how they affect the behavior of the ORM. - **JMX Integration**: Describes how ...

    百度持续交付项目组面试题

    一致性哈希可以确保当增加或删除节点时,只需要重新哈希一小部分数据,而不是整个数据集。 **一致性哈希步骤**: 1. **初始化**:将所有节点映射到一个环形空间上。 2. **添加/删除节点**:新加入或移除的节点只需...

    JAVA工程师面试常见问题及答案

    - **分离(Detached)**: 当一个持久化对象从会话中移除后,它就变成分离状态。此时,对象不再受Hibernate管理。 #### 8. Hibernate锁机制 Hibernate支持多种锁机制,包括乐观锁和悲观锁: - **乐观锁**通常通过...

Global site tag (gtag.js) - Google Analytics