简体   繁体   English

如何检查对象是否在休眠状态下连接到另一个对象

[英]Howto check if a object is connected to another in hibernate

Imagine two domain object classes, A and B . 想象一下两个域对象类AB A has a bidirectional one-to-many relationship to B . AB具有双向一对多关系。 A is related to thousands of B . A与数千B相关。 The relations must be unique, it's not possible to have a duplicate. 关系必须是唯一的,不可能有重复。

To check if an instance of B is already connected to a given instance of A , we could perform an easy INNER JOIN but this will only ensure the already persisted relations. 要检查B的实例是否已经连接到给定的A实例,我们可以执行一个简单的INNER JOIN但这只能确保已经存在的关系。

What about the current transient relations? 目前的暂时关系怎么样?

class A {
   @OneToMany
   private List<B> listOfB;
}

If we access the listOfB and perform a check of contains() this will fetch all the connected instances of B lazy from the datasource. 如果我们访问listOfB并执行contains()检查,这将从数据源获取所有连接的B lazy实例。 I only want to validate them by their primary-key. 我只想通过他们的主键验证它们。

Is there an easy solution where I can do things like " Does this instance of A is connected with this instance of B ? " without loading all these data into memory and performing a lookup based on collections? 是否有一个简单的解决方案,我可以做“ A这个实例是否与B这个实例连接? ”而不将所有这些数据加载到内存并执行基于集合的查找?

Thank you for all the answers. 谢谢你的所有答案。 The extra lazy collection did the trick for me. 额外的懒人收藏为我做了伎俩。 I configured the @OneToMany connection with the LazyCollection annotation. 我使用LazyCollection注释配置了@OneToMany连接。

@IndexColumn(name = "index", base = 1)
@LazyCollection(LazyCollectionOption.EXTRA)

The Hibernate: Extra-lazy collection fetching article helped me doing this. Hibernate:Extra-lazy collection抓取文章帮助我做到了这一点。 When you use this option, #size() , #contains() , #get() , etc. do not trigger collection initialization. 使用此选项时, #size()#contains() #size()#contains() #get()等不会触发集合初始化。

i think it can be done in two steps. 我认为可以分两步完成。 For transient B's, Add your transient B's to listOfB also add to a transient list too. 对于瞬态B,将瞬态B添加到listOfB也会添加到瞬态列表中。 And do your contains checks in this list. 并在此列表中包含检查。

For your persisted B's, use a query something like, 对于你持久的B,使用类似的查询,

select count(*) from B b where b.a.id = :aId

If this query returns zero, you can say that there isn't a relation between A and B. 如果此查询返回零,则可以说A和B之间没有关系。

再考虑一下你的问题的最后一段,因为关联是双向的,我会搜索你的特定B实例与A的关联。

Why can't you perform INNER JOIN ? 你为什么不能进行INNER JOIN

With default flush mode Hibernate will flush the session before executing query, so that unsaved elements of the collection is not a problem. 使用默认刷新模式,Hibernate将在执行查询之前刷新会话,以便集合中未保存的元素不会出现问题。

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

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