开发者

Howto check if a object is connected to another in hibernate

开发者 https://www.devze.com 2023-02-03 09:33 出处:网络
Imagine two domain object classes, A and B. A has a bidirectional one-to-many relationship to B. A is related to thousands of 开发者_运维百科B. The relations must be unique, it\'s not possible to have

Imagine two domain object classes, A and B. A has a bidirectional one-to-many relationship to B. A is related to thousands of 开发者_运维百科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.

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. 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?


Thank you for all the answers. The extra lazy collection did the trick for me. I configured the @OneToMany connection with the LazyCollection annotation.

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

The Hibernate: Extra-lazy collection fetching article helped me doing this. When you use this option, #size(), #contains(), #get(), etc. do not trigger collection initialization.


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. And do your contains checks in this list.

For your persisted B's, use a query something like,

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.


Thinking about the last paragraph of your question some more, since the association is bidirectional, I would do a search on your specific instance of B with an association to A.


Why can't you perform 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消