Marcel Stör
Marcel Stör

Reputation: 23555

JPA: directly mapping collection size to attribute using count?

Class A has a one-to-many relationship to B. Hence, A has an attribute collectionOfB.

Is there any way I could map "count B" to single attribute in A?

The purpose would be to offer a shortcut to retrieve the number of associated Bs without loading the entire collection. Sometimes all I need is the count i.e. the collection size. I know I could issue a query against the entity manager that does exactly that. However, seeing it done by the JPA provider thanks to annotations would of course be preferable.

Upvotes: 6

Views: 4005

Answers (3)

Marcel Stör
Marcel Stör

Reputation: 23555

Possibly this could be achieved using formulas: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-hibspec-property

Upvotes: 0

Marcel Stör
Marcel Stör

Reputation: 23555

I was able to solve my problem using Hibernate's extra-lazy mapping: http://www.frightanic.com/2010/11/21/extra-lazy-one-to-many-mapping-with-hibernate/

Upvotes: 4

SanG
SanG

Reputation: 66

As far I know, this is not possible. As you already suggested, run a query to achieve this, which shouldn't be expensive unless you have hundreds of thousands of B objects and you could still cache it and only update each x minutes.

More error prone solution would be to have a stats entity with these kind of numbers.

Upvotes: 0

Related Questions