Possible Duplicate:
Spring + Hibernate : a different object with the same identifier value was already associated with the session用同樣的標識值不同的對象已經與會話錯誤上保存
我已經與我的休眠註釋問題有關。我有兩個類之間的雙向關係。這裏的映射(感謝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設置爲空...任何幫助表示讚賞。謝謝^ _^...
你確定你沒有初始化'Collection.id'爲0?由於它是自動生成的,所以在保存之前它應該是'null'。 – axtavt 2010-11-16 13:04:59
是的,我不把collection.id設置爲0.感謝您的回覆 – mileesah 2010-11-16 14:03:47