Skip to content

Tag: JPA

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.

No code REST services with Spring Boot and Spring Data REST

CRUD REST services are the backbone of a microservice architecture. If we want to use microservices rather than monolithic applications, it’s essential that we can create a basic service with a minimum of effort. Spring Boot can be used to quickly create and deploy a new web service. Spring Data REST can be used to build out the REST interface based on a database entity model. Using both together allows us to create a running RESTful web service with zero custom Java code and no tricky XML.

This article describes how to build a RESTful web service as an executable JAR that provides CRUD operations against a single MySQL database table.

This demo can be downloaded from GitHub in the Spanners Demo Application version 4.0 (spanners-api module). You can run the working example as a docker-compose stack, along with the associated MySQL database and the Spring MVC web app that consumes the service (see the previous post on docker-compose for details on how to run this).