春天 + Hibernate:具有相同标识符值的不同对象已与会话关联

发布于 2024-08-19 15:44:38 字数 6793 浏览 8 评论 0原文

在我使用 Spring 和 Hibernate 的应用程序中,我解析 CSV 文件,并在每次从 CSV 文件读取记录时调用 handleRow() 来填充数据库。

我的域模型:

“家族”有很多“子家族”

“亚科”有很多“轨迹”

“基因座”属于“物种”

科<->子家族<-> Locus 都是双向映射。

代码:

public void handleRow(Family dummyFamily, SubFamily dummySubFamily, Locus dummyLocus) {
  //Service method which access DAO layers
  CommonService serv = ctx.getCommonService();

  boolean newFamily=false;
  Family family=serv.getFamilyByFamilyId(dummyFamily.getFamilyId());
  if(family==null){
    newFamily=true;
    family=new Family();
    family.setFamilyId(dummyFamily.getFamilyId());
    family.setFamilyIPRId(dummyFamily.getFamilyIPRId());
    family.setFamilyName(dummyFamily.getFamilyName());
    family.setFamilyPattern(dummyFamily.getFamilyPattern());
    family.setRifID(dummyFamily.getRifID());
  }

  SubFamily subFamily = family.getSubFamilyBySubFamilyId( dummySubFamily.getSubFamilyId() );
  if(subFamily==null){   
    subFamily=new SubFamily();
    subFamily.setRifID(dummySubFamily.getRifID());   
    subFamily.setSubFamilyId(dummySubFamily.getSubFamilyId());
    subFamily.setSubFamilyIPRId(dummySubFamily.getSubFamilyIPRId());
    subFamily.setSubFamilyName(dummySubFamily.getSubFamilyName());
    subFamily.setSubFamilyPattern(dummySubFamily.getSubFamilyPattern());

    family.addSubFamily(subFamily);
  }

  //use the save reference, to update from GFF handler
  Locus locus = dummyLocus;

  subFamily.addLocus(locus);

  assignSpecies(serv,locus);
  //Persist object
  if(newFamily){
    serv.createFamily(family);
  } else {
    serv.updateFamily(family);
  }
}

使用以下方法将物种分配给轨迹,该方法仅访问 DAO 层:

private void assignSpecies (CommonService serv, Locus locus) {
  String locusId = locus.getLocusId();
  String speciesId = CommonUtils.getLocusSpecies(locusId, ctx.getSpeciesList()).getSpeciesId();
  //Simply get Species object from DAO
  Species sp = serv.getSpeciesBySpeciesId(speciesId);
  locus.setSpecies(sp);  
}

Hibernate 给出以下错误:

[INFO] Starting scheduled refresh cache with period [5000ms]
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
############################ROW#####################1
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Creating NEW SubFamiyID#######RIF0005913
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Hibernate: insert into family (family_id, rif_iD, family_name, family_ipr_id, family_pattern) values (?, ?, ?, ?, ?)
Hibernate: insert into subfamily (sub_family_id, rif_iD, sub_family_name, sub_family_ipr_id, sub_family_pattern, family_id, sub_family_index) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into locus (locus_id, refTrans_id, function, species_id, sub_family_id, sub_family_index) values (?, ?, ?, ?, ?, ?)
Hibernate: update species set species_id=?, name=? where id=?
Hibernate: update subfamily set family_id=?, sub_family_index=? where id=?
Hibernate: update locus set sub_family_id=?, sub_family_index=? where id=?
############################ROW#####################2
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select subfamilie0_.family_id as family7_1_, subfamilie0_.id as id1_, subfamilie0_.sub_family_index as sub8_1_, subfamilie0_.id as id0_0_, subfamilie0_.sub_family_id as sub2_0_0_, subfamilie0_.rif_iD as rif3_0_0_, subfamilie0_.sub_family_name as sub4_0_0_, subfamilie0_.sub_family_ipr_id as sub5_0_0_, subfamilie0_.sub_family_pattern as sub6_0_0_, subfamilie0_.family_id as family7_0_0_ from subfamily subfamilie0_ where subfamilie0_.family_id=?
Hibernate: select locuslist0_.sub_family_id as sub5_1_, locuslist0_.id as id1_, locuslist0_.sub_family_index as sub7_1_, locuslist0_.id as id2_0_, locuslist0_.locus_id as locus2_2_0_, locuslist0_.refTrans_id as refTrans3_2_0_, locuslist0_.function as function2_0_, locuslist0_.sub_family_id as sub5_2_0_, locuslist0_.species_id as species6_2_0_ from locus locuslist0_ where locuslist0_.sub_family_id=?
Hibernate: select species0_.id as id3_0_, species0_.species_id as species2_3_0_, species0_.name as name3_0_ from species species0_ where species0_.id=?
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Exception in thread "main" [INFO] Closing Compass [compass]
org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
 at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:590)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
 at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
 at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
 at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:218)
 at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268)

有什么提示吗?

In my application, which uses Spring and Hibernate, I parse a CSV file and populate the db by calling handleRow() every time a record is read from the CSV file.

My domain model:

'Family' has many 'SubFamily'

'SubFamily' has many 'Locus'

a 'Locus' belongs to a 'Species'

Family <-> SubFamily <-> Locus are all bi-directional mappings.

Code:

public void handleRow(Family dummyFamily, SubFamily dummySubFamily, Locus dummyLocus) {
  //Service method which access DAO layers
  CommonService serv = ctx.getCommonService();

  boolean newFamily=false;
  Family family=serv.getFamilyByFamilyId(dummyFamily.getFamilyId());
  if(family==null){
    newFamily=true;
    family=new Family();
    family.setFamilyId(dummyFamily.getFamilyId());
    family.setFamilyIPRId(dummyFamily.getFamilyIPRId());
    family.setFamilyName(dummyFamily.getFamilyName());
    family.setFamilyPattern(dummyFamily.getFamilyPattern());
    family.setRifID(dummyFamily.getRifID());
  }

  SubFamily subFamily = family.getSubFamilyBySubFamilyId( dummySubFamily.getSubFamilyId() );
  if(subFamily==null){   
    subFamily=new SubFamily();
    subFamily.setRifID(dummySubFamily.getRifID());   
    subFamily.setSubFamilyId(dummySubFamily.getSubFamilyId());
    subFamily.setSubFamilyIPRId(dummySubFamily.getSubFamilyIPRId());
    subFamily.setSubFamilyName(dummySubFamily.getSubFamilyName());
    subFamily.setSubFamilyPattern(dummySubFamily.getSubFamilyPattern());

    family.addSubFamily(subFamily);
  }

  //use the save reference, to update from GFF handler
  Locus locus = dummyLocus;

  subFamily.addLocus(locus);

  assignSpecies(serv,locus);
  //Persist object
  if(newFamily){
    serv.createFamily(family);
  } else {
    serv.updateFamily(family);
  }
}

a Species is assigned to a Locus using following method, which simply accesses the DAO layer:

private void assignSpecies (CommonService serv, Locus locus) {
  String locusId = locus.getLocusId();
  String speciesId = CommonUtils.getLocusSpecies(locusId, ctx.getSpeciesList()).getSpeciesId();
  //Simply get Species object from DAO
  Species sp = serv.getSpeciesBySpeciesId(speciesId);
  locus.setSpecies(sp);  
}

Hibernate gives following error:

[INFO] Starting scheduled refresh cache with period [5000ms]
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
############################ROW#####################1
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Creating NEW SubFamiyID#######RIF0005913
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Hibernate: insert into family (family_id, rif_iD, family_name, family_ipr_id, family_pattern) values (?, ?, ?, ?, ?)
Hibernate: insert into subfamily (sub_family_id, rif_iD, sub_family_name, sub_family_ipr_id, sub_family_pattern, family_id, sub_family_index) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into locus (locus_id, refTrans_id, function, species_id, sub_family_id, sub_family_index) values (?, ?, ?, ?, ?, ?)
Hibernate: update species set species_id=?, name=? where id=?
Hibernate: update subfamily set family_id=?, sub_family_index=? where id=?
Hibernate: update locus set sub_family_id=?, sub_family_index=? where id=?
############################ROW#####################2
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select subfamilie0_.family_id as family7_1_, subfamilie0_.id as id1_, subfamilie0_.sub_family_index as sub8_1_, subfamilie0_.id as id0_0_, subfamilie0_.sub_family_id as sub2_0_0_, subfamilie0_.rif_iD as rif3_0_0_, subfamilie0_.sub_family_name as sub4_0_0_, subfamilie0_.sub_family_ipr_id as sub5_0_0_, subfamilie0_.sub_family_pattern as sub6_0_0_, subfamilie0_.family_id as family7_0_0_ from subfamily subfamilie0_ where subfamilie0_.family_id=?
Hibernate: select locuslist0_.sub_family_id as sub5_1_, locuslist0_.id as id1_, locuslist0_.sub_family_index as sub7_1_, locuslist0_.id as id2_0_, locuslist0_.locus_id as locus2_2_0_, locuslist0_.refTrans_id as refTrans3_2_0_, locuslist0_.function as function2_0_, locuslist0_.sub_family_id as sub5_2_0_, locuslist0_.species_id as species6_2_0_ from locus locuslist0_ where locuslist0_.sub_family_id=?
Hibernate: select species0_.id as id3_0_, species0_.species_id as species2_3_0_, species0_.name as name3_0_ from species species0_ where species0_.id=?
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Exception in thread "main" [INFO] Closing Compass [compass]
org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
 at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:590)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
 at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
 at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
 at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
 at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:218)
 at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268)

Any tips?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

栖迟 2024-08-26 15:44:38

使用merge()。该异常意味着当前会话已经知道您正在传递的实体。如果没有,请检查您如何覆盖 hashCode()equals() - 它应该为不同的实体返回不同的值。

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.

长安忆 2024-08-26 15:44:38

如果您执行 delete()update(),也可能会遇到此问题。如果您自己构建 hibernate 映射的 pojo(可能是从 DTO),则可能会出现此问题。该 pojo 现在与 Session 中已有的标识符具有相同的标识符,这会导致问题。

您现在有两个选择。要么按照 @Bozho 所说的操作,然后首先 merge() 对象。这负责更新。对于删除,请获取 merge() 返回的对象并将其删除。

另一种选择是首先使用对象的 id 查询 Session,然后删除或更新它。

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.

别低头,皇冠会掉 2024-08-26 15:44:38

当实体的 ID 列没有生成值注释时,我看到了这种情况:

@GeneratedValue(strategy = GenerationType.AUTO)

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

@GeneratedValue(strategy = GenerationType.AUTO)
仲春光 2024-08-26 15:44:38

我是这样解决的:
删除方法:

    this.getHibernateTemplate().clear();

    this.getHibernateTemplate().delete(obj);

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

更新方法:

    this.getHibernateTemplate().merge(obj);

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

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();
猫腻 2024-08-26 15:44:38

如果您要在 saveOrUpdate() 调用之后从会话中更新对象 evict() ,还要检查该对象的 hashCode 实现。

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

一曲琵琶半遮面シ 2024-08-26 15:44:38

您可能创建了 Session 的两个实例。

Session session = factory.openSession();

如果您在一个函数中打开一个会话,并通过创建另一个会话来执行另一个函数,则会出现此问题。

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.

献世佛 2024-08-26 15:44:38

这发生在我身上,因为我的复合键的一部分为空。例如:

    @Id
    @Column(name = "id")
    private String id;

    @JoinColumn(name = "id")
    private Username username;

用户名恰好为空,这导致“重复”空主键,即使 id 不同。

This happened to me because part of my compound key was null. Ex:

    @Id
    @Column(name = "id")
    private String id;

    @JoinColumn(name = "id")
    private Username username;

Username happened to be null which led to "duplicate" null primary keys, even though the id was different.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文