关于a different object with the same identifier value was already associated with the session错误的一种解决方法

今天写程序遇到了一个问题,最后在百度的帮助下解决了,现在拿出来分享一下。

我的程序片段:第一种----------

 1 @Action(value = "/updateEmp", results = {@Result(name = "success", type = "json")})
 2     public String updateEmp() {
 3         Employee emp = new Employee();
 4         if(employee.getDept().getDeptId()==null){
 5             Dept dept = new Dept();
 6             dept = empService.finddeptfdemp(employee.getEmpId());
 7             emp = employee;
 8             emp.setDept(dept);
 9         }
10         
11         System.out.println(emp);
12         System.out.println(employee);
13         if (empService.updateEmp(emp)) {
14             success=true;
15             return "success";
16         } else {
17             return "error";
18         }
19     }

第二种-------------

 1 Employee emp = new Employee();
 2         if(employee.getDept().getDeptId()==null){
 3             employee.setDept(empService.findById(employee).getDept());
 4         }
 5         System.out.println(emp);
 6         System.out.println(employee);
 7         if (empService.updateEmp(employee)) {
 8             success=true;
 9             return "success";
10         } else {
11             return "error";
12         }

 

两个报的错得到的结果一样:

原本是想得到前台修改的信息,但是部门信息不变的,但是报了错:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.lightspeed.entity.Employee#21]

在控制台输出了一下emp和employee结果发现得到的是一样的东西,明明new了一下啊。

信息: Server startup in 7718 ms
com.lightspeed.entity.Employee@2139c8ac
com.lightspeed.entity.Employee@2139c8ac


最后的解决办法是用从表查出来的对象作为要更新的数据才可以:

 1 @Action(value = "/updateEmp", results = {@Result(name = "success", type = "json")})
 2     public String updateEmp() {
 3         Employee emp = new Employee();
 4         if(employee.getDept().getDeptId()==null){
 5             emp = empService.findById(employee);
 6             emp.setEmpSex("v");
 7         }
 8         System.out.println(emp);
 9         System.out.println(employee);
10         if (empService.updateEmp(emp)) {
11             success=true;
12             return "success";
13         } else {
14             return "error";
15         }
16     }

 

这样就可以修改数据了,控制台输出的两个实体也不一样了:

信息: Server startup in 7895 ms
com.lightspeed.entity.Employee@2628a359
com.lightspeed.entity.Employee@6fc99b43

然后就可以成功修改了。

与大家分享一下我的解决办法,并且希望有大神可以讲一下其中的原理.......

 

posted @ 2015-08-23 19:50  择一城终老  阅读(157)  评论(0)    收藏  举报