简体   繁体   English

休眠查询未在同一事务中找到“待定”实体

[英]Hibernate query not finding “pending” entites in same transaction

I've got an app for importing data into a ManyToMany structure. 我有一个用于将数据导入ManyToMany结构的应用程序。

    @Table(name="content")
    class Content {
      @Column(.., unqiue=true)
      String str;
    }

    @Table(name="group")
    class Group {
      @JoinTable("group_content"..)
      List<Content> contentList;
    } 

The Content has a unique column str (as seen above) which is used by the app to identify the content already exist in database - and if so re-use that entity rather than adding it again. Content具有唯一的列str (如上所示),应用程序使用它来标识数据库中已经存在的内容-如果是的话,请重用该实体,而不是再次添加它。

This is done with a findByStr(String str) method in a ContentDao implementation. 这是通过ContentDao实现中的findByStr(String str)方法完成的。 It's implemented as a NamedQuery ( from Content c where c.str = :str ). 它作为NamedQuery实现( from Content c where c.str = :str )。

When I run an import where both groups and content is new and the some groups refeer to the same (new) content it does seem that my findByStr query returns NULL . 当我运行导入时,组和内容都是新的,而某些组重新引用相同(新)的内容,似乎我的findByStr查询似乎返回NULL

The query works fine outside of this scenario but it seems when Content objects has been created, but not committed, the query does not detect them. 在这种情况下,该查询可以正常工作,但是似乎已创建但未提交Content对象时,该查询不会检测到它们。

Currently to work around this I'm actually keeping a Map<String, Content> to double check against if the query returns NULL . 目前,要解决此问题,我实际上是保留Map<String, Content>来仔细检查查询是否返回NULL

Hibernate do not execute all insert statements immidiately. Hibernate不会立即执行所有插入语句。 Make sure that before each call to findByStr all SQL inserts for all new objects are sent to DB. 确保在每次调用findByStr之前,将所有新对象的所有SQL插入都发送到DB。 You can ensure it by doing: 您可以通过执行以下操作来确保它:

  • Tell to Hibernate to take into account all new objects. 告诉Hibernate考虑所有新对象。 For example you can do it by executing session.save(group) for each new group object (which will take into account related content objects) 例如,您可以通过为每个新的组对象执行session.save(group)来做到这一点(它将考虑相关的内容对象)
  • execute one time session.flush() 执行一次session.flush()

Normally after these all changes must be available for your query in the same transaction. 通常,在所有这些更改之后,所有更改必须可用于同一事务中的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM