当前位置: 代码迷 >> J2EE >> JPA错误:org.hibernate.PersistentObjectException: detached entity passed to persist
  详细解决方案

JPA错误:org.hibernate.PersistentObjectException: detached entity passed to persist

热度:483   发布时间:2016-04-22 02:33:43.0
JPA异常:org.hibernate.PersistentObjectException: detached entity passed to persist
这几天老遇到这个异常,还是没有解决,请各位帮忙看下:
(1)异常信息:
Java code
org.springframework.dao.InvalidDataAccessApiUsageException:[color=#FF6600] detached entity passed to persist[/color]: com.myproject.hrsystem.entity.Post; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.myproject.hrsystem.entity.Post

(2)我配的是多对多关系:
Java code
Department类:@ManyToMany(cascade = CascadeType.ALL)    @JoinTable(name = "TBL_DeptPost", joinColumns = { @JoinColumn(name = "dept_ID") }, inverseJoinColumns = { @JoinColumn(name = "post_Id") })    public Set<Post> getPosts() {        return posts;    }Post类:@ManyToMany(mappedBy = "posts",cascade = CascadeType.ALL)    public Set<Department> getDepartments() {        return departments;    }
(3)报错代码:
Java code
Set<Post> posts = new HashSet<Post>();            Company cmp = new Company();// 设置公司信息            cmp.setCmpId(1);            String[] postIds = request.getParameterValues("select2");// 获取部门ID            // 如果职位ID数组不为空,则循环遍历职位数组,取出职位ID            if (StringUtil.isNullOrEmpty(postIds)) {                for (String s : postIds) {                    Integer pid = Integer.parseInt(s); // 获取职位ID                    Post tempPost = new Post();                    System.out.println("职位ID:-----"+pid);                    tempPost.setPostId(pid);                    posts.add(tempPost); // 将职位信息添加到集合中                }            }            dept.setPosts(posts);// 所属职位            dept.setCmp(cmp);// 所属公司            dept.setEmpId(empId);// 部门经理            dept.setAddId(empId);// 建立人            dept.setAddTime(new Date());// 建立时间            dept.setDelSt(0);// 删除标识

我使用的persist方法保存,要是给部门不添加职位的话还可以添加部门信息,但一添加职位就报错了

------解决方案--------------------
貌似是级联配置不对:
把cascade = CascadeType.ALL 改成 cascade=CascadeType.REFRESH 测一下看看。
------解决方案--------------------
远征军同学,好好总结一下级联
  相关解决方案