By Erik Bakker

Counting Hibernate queries in Play

Play 1.2.x uses Hibernate as the default JPA implementation. Hibernate is an impressive tool, but it’s also known to cause problems. At Devoxx, Patrycja Wegrzynowicz stated:

Hibernate is an elegant, straightforward, and easy to use library. This is undeniably true for simple domain models. What about more complex ones? It turns out that in case of complex domain models we usually run into interesting performance issues.

In particular, Hibernate sometimes executes way more queries than you would expect. Wegrzynowicz showed that is not just the easy to reason about and common N+1 select problem, but that there are some real puzzlers. You can view her presentation at the Devoxx website.

Lord Kelvin once said “To measure is to know”, and measuring the number of queries that Hibernate executes in a Play application is not something that comes out of the box. That is why I created the Play jpa-stats module, which extracts various numbers from Hibernate’s internals, and makes them available as template tags. After installation of the module, you can use the following tag in your templates:

#{jpastats.databaseQueries /}

Alternatively, you have the numbers outputted as headers on the HTTP response. This is very useful if the request doesn’t result in a page, but in some JSON for an Ajax call for example. Finally, you can also retrieve the numbers with methods calls like JPAStatsPlugin.getDatabaseQueryCount();

For more information, see the project on Github, or the documentation on Github or on the Play module repository website

About me

photo of meHi, my name is Erik Bakker and I'm a software engineer, working mostly with Scala. I'm co-authoring the book Play for Scala. On this page, I blog on software related topics.

Recent posts

Archive

Book

Play for Scala cover imagePlay for Scala is currently in the Manning Early Access Program. You can order and start reading the finished chapters immediately. The first chapter is free!

Contact

I'm @eamelink on Twitter.

You can also find me on GitHub, LinkedIn and Google.