Atticus
Atticus

Reputation: 1632

Hql query optimization - return indexed id or the whole object

I have a databas table with cca. 327 000 entries. (SQL Server 2005, Hibernate 3) I have to generate a report that queries this table for 300 times. The Hql query looks like this:

select hist from HistoryTable hist where year(hist.date) = :year and 
        hist.user.userId = :userId and hist.entryType = :created

I need to wait 3 minutes for the report to be generated, so is there a way to optimize this query to run faster? I though of returning the hist.id (because that is a primary key therefore it is indexed and I guess it is looked up faster) instead of the whole hist object and then retrieve the History object via its id? Maybe Hibernate does the same thing, and this is not neccessary, and then there is nothing to be done. Any ideas?

Upvotes: 1

Views: 788

Answers (2)

joostschouten
joostschouten

Reputation: 3893

Also make sure your associations (eg hist.user, hist.user.somethingElseYetAgain) are loaded lazily and not eager. Otherwise your queries will join a lot more than is needed and instantiate instances in stead of Object proxies.

This can be indicated at the query or mapping level.

Upvotes: 0

sbrattla
sbrattla

Reputation: 5386

I don't think it will help you that much to first retrieve the primary keys. That will only add to the number of queries you need to run (and consequently the time it takes).

I'd rather have a look at the report and see if the number of queries could be reduced. Furthermore, i'd consider retrieving scalar values instead of full object instances if you are dealing with a large number of objects (Hibernate comes with an overhead compared to retrieving plain values from a database).

I'd also make sure that all tables are properly indexed (test the queries and see how they perform).

Upvotes: 1

Related Questions