zoukankan      html  css  js  c++  java
  • a different object with the same identifier value was already associated withthe session异常解决方案

    异常信息:

    org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated withthe session

    发生原因:

    在对一个实体查询操作后,进行了set,然后又要对这个实体进行save/update,

    报错的例子

    //Service层
    public void modifyPersonalizedSettings(PersonalizedSettings ps,Integer userId)throws Exception {
    		
    		User user = personalizedSettingsDAO.selectUserById(userId);
    		ps.setUser(user);
    		personalizedSettingsDAO.updatePersonalizedSettings(ps);
    	}
    //DAO层
    public void updatePersonalizedSettings(PersonalizedSettings ps) throws Exception {
    System.out.println(ps+"DAO");
    template.merge(ps);
    }

    解决方案:

    最简单的就是不用save()方法,改用merge()方法。

    例子:

    //Service层
    public void modifyPersonalizedSettings(PersonalizedSettings ps,Integer userId)throws Exception {
    		
    		User user = personalizedSettingsDAO.selectUserById(userId);
    		ps.setUser(user);
    		personalizedSettingsDAO.updatePersonalizedSettings(ps);
    	}
    //DAO层
    public void updatePersonalizedSettings(PersonalizedSettings ps) throws Exception {
    System.out.println(ps+"DAO");
    //template.update(ps)不再使用update()方法,改用merge()方法即可
    template.merge(ps);
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Leetcode95. Unique Binary Search Trees II不同的二叉搜索树2
    Leetcode134. Gas Station加油站
    Leetcode152. Maximum Product Subarray乘积的最大子序列
    C#扩展方法
    Lua语言入门
    Docker命令
    SpringBoot-配置文件属性注入-3种方式
    从零开始学Linux系统(五)用户管理和权限管理
    MyCat学习笔记
    kafka-zk-安装测试初体验
  • 原文地址:https://www.cnblogs.com/codingcloud/p/5262982.html
Copyright © 2011-2022 走看看