4

可能重复:
Spring + 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 ...感谢您的帮助。谢谢^_^...

4

1 回答 1

5

上的mappedby注释Receipt意味着Collection实际上是关系的拥有方,这显然不是您想要的,因为您在Receipt.

您应该从 hibernate 文档中删除mappedbyon theReceipt并遵循此示例:

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

@Entity 
public class Collection implements Serializable { 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @ManyToOne 
    @JoinColumn(name="ReceiptId",insertable=false,updatable=false) 
    private Receipt receipt; 
    ...
}

使用上面相同的代码来执行保存应该可以工作。

这里有更多关于此的信息:http: //docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/

于 2010-11-16T17:21:35.607 回答