views:

78

answers:

2

We have an JPA @Entity class (say User) which has a @ManyToOne reference (say Address) loaded using the EAGER option which in turn loads it's own @ManyToOne fields (say Country) in a EAGER fashion.

We use the EntityQuery interface to count the list of User's based on a search criteria, during such a load all the @ManyToOne fields which have been marked as EAGER get loaded. But in order to perform a EntityQuery.resultCount(), I actually don't need to load the @ManyToOne fields. Is there a way to prevent loading of the EAGER fields in such cases so that we can avoid the unnecessary joins?

+3  A: 

If you want to get the number of rows only, use the COUNT aggregate function, rather than getResultCount().

Otherwise, you can switch the default behaviour to lazy, and load the items by calling Hibernate.initialize(entity). But that's tedious.

Bozho
trying to initialize entities is quite error prone, i wouldn't want to venture down that path. I would also prefer the code to be implementation agnostic as possible.
Samuel
well, COUNT is rather standard.
Bozho
+2  A: 

Why don't you use aggregate functions(COUNT in your case) if all you need is the number of records ?

a1ex07