Hands-on Spring Data JPA

This is your guide to get Hands-on Spring Data JPA. It gives an Introduction to Spring Data JPA and provides easy code examples. At the end of this series of tutorials your will be able to write your own Spring Application and access databases.

Prerequisite to Learn Spring Data JPA

If you are here, to Learn Spring Data JPA you need to have basic understanding on Databases and SQL queries. In addition, below are essential prerequisites.

  1. Know Spring framework. Because, It is mandatory to have basic understanding of Spring Architecture.
  2. Know, how to use Spring JdbcTemplate. Not mandatory, but good to have. Because, to truly understand the ease a framework provides, It is always good to know the harder way of doing the things. It helps you to know why to use a certain framework rather than just following expert recommendations.
  3. Most of our code examples use Spring Boot. Spring boot is an easy and quick way to create and run an application and focus only on the business. But, each code example, we demonstrate in this series can be re-written without Spring Boot.

Apart from this, we also expect you to follow the in-lines links appeared in the tutorial below.

Know the Jargons

To Learn Spring Data JPA, It is extremely important to get familiar some of the Unknowns. To begin with, we will introduce you to some of the major key players. As we move forward we will know more and more things as and when they appear.

Java Persistence API

Java Persistence API, defines Specifications for accessing and persisting data into databases. JPA was initially part of Enterprise Java Beans (EJB) specifications, and later released as an independent specification.

Objet Relational Mapping (ORM)

The Object Relational Mapping is the base of JPA. Which, is all about representing and accessing data in the form of plain Java Objects – called as Entities. Hibernate, EclipseLink and Apache OpenJPA are some of the JPA implementations available in market. Out of which, Hibernate is more popular and widely used.


Entities are plain Java Objects designated to represent database entities. All of the non-transient fields of Entity objects are persisted by the JPA implementations.

Spring JPA Support

Spring Framework is one of the most popular Java Frameworks. It has number of projects under the umbrella and specialised in providing abstractions, or utilities for almost all of the technologies that are related to Java.

Spring Data JPA, has got a concept of Repository interfaces which declare query methods, and Spring implements these interfaces at runtime.

The project Spring Data deals with accessing data from all the different types of data stores including SQL and No SQL. While, Spring Data JPA is a sub-project of Spring data, and specialises in sql databases.
Consider Reading What is JPA, Spring Data and Spring Data JPA.


The Repositories are represented in the form of interfaces. Where, the interfaces and their runtime implementations (provided by Spring), replace the DAO layer in your application.

Query Methods

The Query Methods are methods defined in repository interfaces. They have a standard naming structure – based on which Spring derives SQL statement at runtime.

Learn to use Entity Manager

Entity Manager is a component in JPA specifications which is a front face of the framework. Entity Manager is responsible for storing and retrieving entities.

Let’s write some code now. Firstly, we Create a Simple Spring Boot Project, have correct dependencies and datasource configurations. After that, @autowire the Entity Manager in your Dao.

@Component public class UserDao { @Autowired EntityManager entityManager; public void addUser(User user) { entityManager.persist(user); } public void updateUser(User user) { User dbUser = entityManager.find(User.class, user.getId()); dbUser.setFirstName(user.getFirstName()); dbUser.setLastName(user.getLastName()); entityManager.persist(dbUser); } public User getUserById(Long id) { return entityManager.find(User.class, id); } public List<User> findUsersByFirstName(String firstName) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> userRoot = cq.from(User.class); Predicate predicate = cb.equal(userRoot.get("firstName"), firstName); entityManager.createQuery(cq.where(predicate)).getResultList(); } public void deleteUser(Long id) { User user = entityManager.find(User.class, id); entityManager.remove(user); } }
Code language: Java (java)

This Dao class is actually doing sort of CRUD on User table. But, there are no SQL queries and it is all about Java API. By default, Spring Data JPA uses Hibernate as its JPA implementation. However, a different implementation can be configured easily. The underlying JPA framework parses these API method calls into native SQL statements.

We have seen example of simple queries and Criteria Queries. In addition, if you chose to write your own SQL queries you can use Java Persistence Query Language (JPQL) & Named Query.

By now, you have an idea about Spring Boot, JPA, Entity and Entity Manager. Also, You learnt how to create queries using API methods. It is time to move forward. The problem working with Entity Manager is, to write complex queries. For instance, consider you have multiple filters, and/or, or sorting the API calls look really bulky and ugly. It kills the readability and hence maintainability.

Learn Spring Data JPA

By now, we assume you understood the JPA, ORM, and also tried with the provided code examples. You have also learnt the benefits of Entity Managers and also the complexity it may inject for complex queries. Next, it is time for you to see how Spring Data JPA frees you from all of this.

Repository Example

Let’s rewrite the same CRUD example for User table. The below interface is doing everything that we did in the earlier example.

@Repository public interface UserRepository extends CrudRepository<User, Long> { User save(User user); Optional<User> findById(Long id); void deleteById(Long id); List<User> findByFirstName(String firstName); }
Code language: Java (java)

Wait !! But it’s just an Interface. Where is actual implementation of these methods ?
You don’t have to provide any implementation. Because, Spring provides it at runtime. The methods declared in repository interfaces are called as query methods. Because, based on the name, parameters, and return types of the methods, Spring knows what do you want to do, and prepares actual SQL statement under the hood.

Try Hands On

Before we end, we recommend you to write your own Spring boot application, that actually access data from a database. For that, please refer to Spring Data JPA with Spring Boot tutorial. Currently, our example use MySQL database. However, if you don’t have MySQL you can simply use H2 database.

Dive Deeper and Deeper

This is the end of this guide. To Sum up, now you know all the basics of JPA and Spring Data JPA. Firstly, you learnt how to represent your database table in the form of an Entity along with Repository interface. You also learnt having repository interface, frees you from using Entity Manager and the query API.

To take you further in specific use cases, we refer you to below tutorials.

Entities with Composite Primary Key
Query an Entity with only few columns of a Composite Primary Key
Pagination and Sorting the results

External Resources

Below are few resources to Learn Spring Data for your further self-study.