I have a class A which have a list of B elements.
In my A class i would like to add:
int size;
which will be valued with the number of B elements. So when I would call myA.getSize()
I will have it.
Is it possible to 开发者_开发技巧map a count query with a single property in the hibernate mapping?
I don't want to load the list that is why i would like to add a size property.
Is it possible to map a count query with a single property in the hibernate mapping?
Yes, use a formula:
<property name="size" type="integer"
formula="( select count(a.getBs) from A a where a.id = aid )">
</property>
More examples in Example: Various Mappings.
Another approach is to use lazy=extra on the collection. This is barely mentioned in the reference documentation and explained further here.
Use lazy="extra" on collections for "smart" collection behavior, i.e. some collection operations such as size(), contains(), get(), etc. do not trigger collection initialization. This is only sensible for very large collections.
精彩评论