views:

87

answers:

2

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.

+3  A: 

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.

Pascal Thivent
@Pascal: is it possible to do the same with JPA annotations?
Roman
@Roman Hibernate has a `@Formula` annotation but this is an extension to JPA.
Pascal Thivent
+1  A: 

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.

Lachlan Roche