有一个没有任何外键的表,每次用hibernate自带的save方法添加实体,只有项目部署后的第一次有效,当再次调用save方法时就会报错:严重: Servlet.service() for servlet annomvc threw exception
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.test.entity.UserInfoEntity#0]
save方法:public void save(BaseEntity entity){
        Session session = null;
        Transaction tx = null;
        try{
            session = HibernateUtil.currentSession();
            tx = session.beginTransaction();
        }catch(Exception e){
            e.printStackTrace();
        }
        session.save(entity);
        tx.commit();
    }
请问是何故?

解决方案 »

  1.   

    hibernate表映射的配置是怎么配的
      

  2.   

    你应该在hibernate的domain的配置文件中配置一个主键,并且设置主键生成策略为native,这样在mysql中就是自动增长了的,不需要你关心主键的值了。在hibernate中是需要设置主键的,你不设置主键,试问一下,你调用saveorupdate方法hibernate应该怎么做呢,岂不是被你弄疯了?另外,不提供主键也不能实现hibernate的自动脏数据检查,哎呀,光问题
      

  3.   

    a different object with the same identifier value was already associated with   这么明显的错误。。
      

  4.   

    这是由于缓存引起来,你的对象 应该是直接传来的
    对象最好new下,你重新set到你自己new的实体中,就可以了
      

  5.   

    看你hibernate里面的配置方法,如果设置为自增长 
    assigned 为你程序里面自己设置
    identity  是数据库的自动生长机制
    sequence  采用数据库的序列生成主键
    native  自行判断,代理主键。
    再一个,检查一下主键的数据类型
    如下是根据序列生成主键:
    <id name="id" type="java.lang.Long">
    <column name="ID" precision="16" scale="0" />
    <generator class="sequence">
    <param name="sequence">SEQ_ID</param>
    </generator>
    </id>