Search code examples
mysqlhibernateobject-construction

Speeding up Hibernate Object creation?


We use Hibernate as our ORM layer on top of a MySQL database. We have quite a few model objects, of which some are quite large (in terms of number of fields etc.). Some of our queries requires that a lot (if not all) of the model objects are retrieved from the database, to do various calculations on them.

We have lazy loading enabled, but in some cases it still takes a significant amount of time for Hibernate to populate the objects. The execution time of the MySQL query is very fast (in the order of a few milliseconds), but then Hibernate takes its sweet time to populate the objects.

Is there any way / pattern / optimization to speed up this process?

Thanks.


Solution

  • One approach is to not populate the entity but some kind of view object.

    Assuming a CustomerView has the appropriate constructor, you can do

    select new CustomerView(c.firstname, c.lastname, c.age) from Customer c
    

    Though I'm a bit surprised about Hibernate being slow to populate objects unless you happen to load associated objects by cascade and forget a few appropriate fetches.