引用:https://blog.csdn.net/zhanggnol/article/details/6307936

常用数据库表的删除办法,一般都会在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后返回的新对象才是允许删除的。

jpa删除根据对象删除失败,报Removing a detached instance 错的更多相关文章

  1. c#封装DBHelper类 c# 图片加水印 (摘)C#生成随机数的三种方法 使用LINQ、Lambda 表达式 、委托快速比较两个集合,找出需要新增、修改、删除的对象 c# 制作正方形图片 JavaScript 事件循环及异步原理(完全指北)

    c#封装DBHelper类   public enum EffentNextType { /// <summary> /// 对其他语句无任何影响 /// </summary> ...

  2. hibernate有关联关系删除子表时可能会报错,可以用个clear避免错误

    //清除子表数据 public SalesSet removeSalesSetDistributor(SalesSet salesSet ){ List<SalesSetDistributor& ...

  3. C++:如何删除string对象的末尾非数字字符

    功能实现: 现有一个string对象包含数字字符以及非数字字符,实现删除string对象的末尾非数字字符. 实例: 输入为"0 1 1 2 3    " 输出为"0 1 ...

  4. 删除JavaScript对象中的元素

    参考http://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object 通过dojo ...

  5. Linux删除ORACLE数据库用户失败提示ORA-01940解决方法

    操作环境 SuSE11+Oracle11gR2 问题现象 删除ORACLE数据库用户失败,提示ORA-01940: cannot drop a user that is currently conne ...

  6. 使用LINQ、Lambda 表达式 、委托快速比较两个集合,找出需要新增、修改、删除的对象

    本文需要对C#里的LINQ.Lambda 表达式 .委托有一定了解. 在工作中,经常遇到需要对比两个集合的场景,如: 页面集合数据修改,需要保存到数据库 全量同步上游数据到本系统数据库 在这些场景中, ...

  7. 创建/读取/删除Session对象

    //创建Session对象 Session["userName"] = "顾德博";//保存,这里可以存储任意类型的数据,包括对象.集合等 Session.Ti ...

  8. unity编辑器扩展_05(删除游戏对象并具有撤回功能)

    代码: [MenuItem("Tools/Delete",false,1)]    static void Delete()    {        GameObject[] go ...

  9. 使用thinkPHP框架实现删除和批量删除一例【原创】

    本文为作者原创,转载请注明原作者及转载地址. 上一篇讲了如何用thinkPHP框架实现数据的添加,那这一篇就讲一下如何用thinkPHP实现数据的删除和批量删除吧. 预期效果图: 原谅博主对照片的处理 ...

随机推荐

  1. 第1节 flume:4、离线项目处理的整个架构图;5、flume的基本介绍;

    第1节 flume:4.离线项目处理的整个架构图 辅助系统工具:flume,azkaban,sqoop. 在一个完整的离线大数据处理系统中,除了hdfs+mapreduce+hive组成分析系统的核心 ...

  2. 使用html2canvas实现网页截图,并嵌入到PDF

    使用html2canvas实现网页截图并嵌入到PDF 以前我们只能通过截图工具进行截取图像.这使得在业务生产中,变得越来越不方便.目前的浏览器功能越来越强大,H5也逐渐普及,浏览器也可以实现截图了.这 ...

  3. 退役选手ZlycerQan的强大的的高精度

    #include <cstdio> #include <iostream> #include <vector> #include <iomanip> # ...

  4. markdown pad激活

    <iframe src="></iframe> ---恢复内容开始--- 注册码 Soar360@live.com GBPduHjWfJU1mZqcPM3BikjYK ...

  5. 条款36:绝不重新定义继承而来的non-virtual函数(Never redefine an inherited non-virtual function)

    NOTE: 1.绝对不要重新定义继承而来的non-virtual函数.

  6. 剑指Offer(书):矩阵中的路径

    题目: * 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径.* 路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子.* 如果一条路径经 ...

  7. SpringMVC中controller的跳转

    controller中的重定向 (1)不需要传递参数重定向 方式一:使用ModelAndView        return new ModelAndView("redirect:/toLi ...

  8. c++ 高精度 加减乘除 四则运算 代码实现

    很久以前写的啦 记得写了好久好久一直卡在特例的数据上面 想起都心塞 那时候变量和数组的取名对我来说简直是个大难题啊 完全乱来 abcdef就一路排下来 自己看的时候都搞不懂分别代表什么 好在后来英语学 ...

  9. 【MVC】使用笔记

    1,在ASP.NET MVC中,路由机制特别碉堡,直接对应于动作方法.没有必要给每一个动作方法添加视图,当视图返回View时,路由系统会自动寻找指定目录下的视图资源. public ViewResul ...

  10. NYOJ 239 月老的难题

    月老的难题 时间限制:1000 ms  |  内存限制:65535 KB 难度:4   描述 月老准备给n个女孩与n个男孩牵红线,成就一对对美好的姻缘. 现在,由于一些原因,部分男孩与女孩可能结成幸福 ...