Hands-on Spring Data JPA

This article is your guide to getting 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 Spring Application and access databases.

Prerequisite to Learn Spring Data JPA

If you are here to Learn Spring Data JPA, you need to understand databases and SQL queries. In addition, below are essential prerequisites.

  1. Know Spring framework. That is because it is mandatory to have a 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 more complicated way of doing things. It helps you understand why to use a specific framework rather than follow 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, we can rewrite each code example we demonstrate in this series without Spring Boot.

Apart from this, we also expect you to follow the in-line links this tutorial provides.

Know the Jargons

To Learn Spring Data JPA, getting familiar with some unknowns is essential. To begin with, we will introduce you to some of the primary vital 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 then Javareleased it as an independent specification.

Objet Relational Mapping (ORM)

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


Entities are plain Java Objects designated to represent database entities. The JPA implementations persist all (non-transient) fields of entity objects.

Spring JPA Support

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

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

The Spring Data project deals with accessing data from different data stores, including SQL and No SQL. At the same time, Spring Data JPA is a Spring Data sub-project specializing in SQL databases.
Consider Reading What is JPA, Spring Data, and Spring Data JPA.


The Repository interface represents all the data repositories. 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 statements at runtime.

Learn to use Entity Manager

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

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

public class UserDao {
    @Autowired EntityManager entityManager;
    public void addUser(User user) {
    public void updateUser(User user) {
        User dbUser = entityManager.find(User.class, user.getId());
    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);
    public void deleteUser(Long id) {
        User user = entityManager.find(User.class, id);
}Code language: Java (java)

This Dao class is performing a sort of CRUD on the 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, we can easily configure a different implementation. The underlying JPA framework parses these API method calls into native SQL statements.

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

You have an idea about Spring Boot, JPA, Entity, and Entity Manager. Also, You learned how to create queries using API methods. It is time to move forward. The problem with working with Entity Manager is writing complex queries. For instance, the API calls look bulky and ugly when you have multiple filters and field-level soring. It kills readability and hence maintainability.

Learn Spring Data JPA

By now, we assume you understood the JPA, and ORM and also tried the provided code examples. You have also learned the benefits of Entity Managers and the complexity they may inject into 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 the User table. The below interface is doing everything that we did in the earlier example.

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 the actual implementation of these methods?
You don’t have to provide any implementation as Spring provides that at runtime. The methods declared in repository interfaces are called query methods. Because, based on the methods’ names, parameters, and return types, Spring knows what you want to do and prepares the actual SQL statement under the hood.

Try Hands-On

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

Dive Deeper and Deeper

Here is the end of this guide. To Sum up, now you know all the basics of JPA and Spring Data JPA. Firstly, you learned how to represent your database table in the form of an Entity along with a Repository interface. A repository interface frees you from using Entity Manager and the Query API.

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

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

External Resources

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