引用: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. Hibernate-02 HQL实用技术

    学习任务 Query接口的使用 HQL基本用法 动态参数绑定查询 HQL的使用 Hibernate支持三种查询方式:HQL查询.Criateria查询.Native SQL查询. HQL是Hibern ...

  2. dns config

    .: { forward . { force_tcp expire 50s health_check 50s } cache debug errors whoami log } Corefile .: ...

  3. saltstack install on centos7

    saltstack offical website reference blog summary install virtualbox yum install VirtualBox-5.2 insta ...

  4. SVN 初级教程

    版本控制器:SVN 1.SVN 作用? 备份.代码还原.协同修改.多版本项目文件管理.追溯问题代码的编写人和编写时间.权限控制等. 2.版本控制简介 2.1 版本控制[Revision control ...

  5. css 实践记录

    子绝父相 https://developer.mozilla.org/zh-CN/docs/Web/CSS/position 利用子绝父相来实现一种比较老的居中方式:1.明确宽度:2.定位左边到容器的 ...

  6. LeetCode(11) Container With Most Water

    题目 Given n non-negative integers a1, a2, -, an, where each represents a point at coordinate (i, ai). ...

  7. sql中getdate()&convert的使用

    1,sql中getdate()函数的使用: getdate()函数从SQL Server中返回当前的时间和日期,如: insert into T3(ID,AddTime) values(,GETDAT ...

  8. [HNOI2009]梦幻布丁(链表+启发式合并)

    洛谷传送门 开始一个O(n^2)思路,每次每句要改变颜色的点,改变完颜色后重新计算颜色的段数,显然拉闸. 然后呢..然后就不会了. 看了别人博客,才知道有个叫做启发式合并的东西,就是把小的合并到大的上 ...

  9. hdu 1501 基本搜索深搜

    #include<stdio.h> #include<string.h> char s1[300],s2[300],s[500]; int len1,len2,len3,fla ...

  10. hdu4352 XHXJ's LIS(数位DP + LIS + 状态压缩)

    #define xhxj (Xin Hang senior sister(学姐)) If you do not know xhxj, then carefully reading the entire ...