Skip to content

Tag: hibernate

JPA native queries with eager fetch and @SqlResultMapping

JPA supports eager and lazy fetch of child entities. If you’re not careful with the lazy fetch strategy it can result in excessive queries as it needs to execute a query for the parent entity and then an additional one for each child. This is the so-called n+1 problem. You’ll often want to use eager fetching so that you can pull the parent and all children with a single query.

If you use HQL/JPQL, the JPA Criteria API or queries derived from Spring Data Repository method names, JPA will convert your SQL query result set to entity objects. That’s what an Object Relational Mapping (ORM) system is for. However if you use JPA native queries (SQL), you’ll need to map the results yourself.

In this post, I’ll look at how to run eager fetches for JPQL and native queries and how to manage the results.

Generate database schema DDL from Hibernate hbm mappings

Hibernate can be used to map Java classes to existing database tables. More often, the Java classes come first and the database is created around the mapping. If that’s the case, you’ll want to define your database schema directly from Hibernate mappings rather than hand crafting DDL scripts. Hibernate offers a couple of ways to do this.


I’ve decided to revisit the JUnit testing Hibernate and Spring recipe that I posted a while back. A problem with the previous recipe is that it did not provide any means to initialize the test database. This wasn’t too much of a problem as I was mostly testing the data insert operations of the DAOs. I then used the same DAO to retrieve the newly inserted data and tested what came back. However this is no good if I don’t want insert operations on my DAO (if it’s to retrieve read only data from the database) or if I want to test the retrieval operations independently of the insert operations.

This post extends the recipe to include a means of initialising the database using DbUnit.

JUnit testing Hibernate and Spring

Here’s a nice recipe for unit testing Spring configured Hibernate. It allows me to neatly test my Spring configured DAOs and reuse a lot of the Hibernate Session and Transaction configuration beans from my production code. This saves having to rewrite it for my tests and also makes the tests more realistic. I’d rather test my production code rather than use mocks as far as possible.