JavaSpringTechnology

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

Spring Data JPA is all about accessing data from databases and you need to have understanding of databases and SQL queries. Apart from this, below are essential prerequisites.

  1. Know Spring framework. It is mandatory to have basic understanding of Spring Architecture.
  2. Know, how to use Spring JdbcTemplate. Not mandatory but good to have. It is always good to know the harder way of doing the things to truly understand the ease any framework provides. 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

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)

Object Relational Mapping is the base of JPA. The ORM 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

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. 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.

Repository

The Repositories are represented in the form of interfaces. These interface 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. Create a Simple Spring Boot Project, have correct dependencies and datasource configurations. Once you are done with this, you can @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);
    }
}

This Dao class is actually doing sort of CRUD on User table. There are no SQL queries and it is all about Java API. By default, Spring Data JPA uses Hibernate as its JPA implementation, however that is configurable. The underlying JPA framework parses these API method calls into native SQL statements.

We have seen example of simple queries and Criteria Queries. 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. You learnt how to create queries using API methods. It is now time to move forward. The problem working with Entity Manager is, writing complex queries. If we have multiple filters, and/or, or sorting the API calls look really bulky and ugly. It kills the readability and hence maintainability.

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. Now, 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);
}

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

Try Hands On

We recommend you to refer Spring Data JPA with Spring Boot tutorial and create a spring Spring boot Application that actually access data from a database. Currently our examples use MySQL database. If you don’t have a MySql database you can start one with docker. Or simply user H2 database. H2 is an in-memory database.

Dive Deeper and Deeper

You now know all the basics of JPA and Spring Data JPA, and also know how to represent your database table in the form of an Entity along with Repository interface. You know 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 the recommended resources for further self-study.

Leave a Reply

Your email address will not be published. Required fields are marked *