Spring + Hibernate : a different object with the same identifier value was already associated with the session

六月ゝ 毕业季﹏ 提交于 2019-11-26 17:49:52

Use merge(). The exception means that the current session is already aware of the entity you are passing. If not, check how you have overridden hashCode() and equals() - it should return different values for different entities.

You can also encounter this problem if you are doing a delete() or update(). The problem is likely to occur if you build the hibernate-mapped pojo yourself, perhaps from a DTO. This pojo now has the same identifier as one that is already in the Session, and that causes the problem.

You now have two options. Either do what @Bozho said and first merge() the object. That takes care of updating. For deleting, take the object returned by merge() and delete it.

The other option is to first query the Session using the id of the object and then delete or update it.

I resolved so: On delete method:

    this.getHibernateTemplate().clear();

    this.getHibernateTemplate().delete(obj);

    // Esta línea realiza el "commit" del comando
    this.getHibernateTemplate().flush();

On update method:

    this.getHibernateTemplate().merge(obj);

    // Esta línea realiza el "commit" del comando
    this.getHibernateTemplate().flush();

I have seen this when an Entity does not have a GeneratedValue annotation for its ID column:

@GeneratedValue(strategy = GenerationType.AUTO)

If you are updating an object evict() it from session after the saveOrUpdate() call, also check your hashCode implementation of the object.

Manas Ranjan Mahapatra

You may have created two instances of Session

Session session = factory.openSession();

If you have opened one session in one function and executing another function with creating another session, then this problem occurs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!