具有相同标识符值的不同对象已与保存时的会话错误相关联

时间:2010-11-16 12:57:38

标签: hibernate spring annotations hibernate-annotations

  

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

我的hibernate注释一直存在问题。我有两个班级之间的双向关系。这是映射(感谢axtavt):

@Entity 
public class Receipt implements Serializable { 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "receipt")
    private List<Collection> collections; 
    ...
}      

@Entity 
public class Collection implements Serializable { 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @ManyToOne 
    @JoinColumn(name="ReceiptId") 
    private Receipt receipt; 
    ...
}

但是,当我尝试使用以下内容保存收据时,收据列表为:

Receipt r = new Receipt();
List<Collection> cols = new ArrayList<Collection>();
cols.add(new Collection());
r.setCollections(cols);
getHibernateTemplate().save(r);

它会生成此错误:

org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: [com.coa.acctreports.pojo.Collection#0]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.coa.acctreports.pojo.Collection#0]
 at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
 at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
 at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
 at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
 at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683)
 at com.coa.acctreports.daoImp.AccountingReportsImpl.save(AccountingReportsImpl.java:35)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

但是当我把它改为

session.merge(receipt)

它没有错误但是当我检查我的数据库时,colllections表上的receiptId fk被设置为null ...感谢任何帮助。谢谢^ _ ^ ...

1 个答案:

答案 0 :(得分:4)

mappedby上的Receipt注释意味着Collection实际上是关系的拥有方,这显然不是您的意图,因为您在{{{ 1}}。

您应该删除Receipt上的mappedby并按照hibernate文档中的示例进行操作:

Receipt

使用上面执行保存的相同代码可以正常工作。

此处有更多相关信息:http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/