JavaSpringTechnology

What is JPA, Spring Data and Spring Data JPA

Learn What is JPA, Spring Data and Spring Data JPA. Read it to understand each of them and how do they work together. Learn the benefits of JPA and hot Spring Data JPA provide easy to use abstractions.

Many of the developers worldwide use Spring JPA. However for many people, it is always unclear how Spring Data JPA is related to JPA Specification. Is it a JPA Implementation? and what role does Hibernate plays beneath. This article focuses on getting this clarity. 

1 Spring Data

The Spring Data is too broad for the scope of this article. This article focuses on JPA and Spring Data JPA.

Spring Data is a project driven by Spring which aims at providing a consistent data access layer for various data-stores, right from relational to no-sql databases.

Background

In a last decade or two the World of Data has seen a big growth. As the data grew, grew the need for faster processing mechanisms and hence specialised storages were invented. Then we got graph stores, document stores, key-value stores and column stores. The specialised stores support specific use cases or specific type of data. They don’t claim to be a one stop solution for storing all types of data in an application. This gave birth to the concept of Polyglot Persistence.

The downside was, different storage technologies means different APIs, different configurations, and different methods. The JDBC and JPA provides a standardisation across SQL datastores. For the specialised storages, there is no standard specification. Most of the organisations were reluctant to embarrass Polyglot Persistence or even introduction of any single non RDBMS datastore into the system (many organisations are still). The main reasons behind this are: having no standards across the datastores and the necessary learning curve.

This is where Spring Data comes into the picture. Don’t get this wrong. Spring Data is NOT a Specification or Standard. Spring data is an Abstraction. It is an umbrella project that has number of modules (like spring-data-redis, spring-data-mongo etc) and a core module called as spring-data-commons. This abstraction tries to bring consistency between the ways we access data on multiple datastores.

The Spring-Data is an umbrella project having number of sub-projects or modules all aimed towards providing uniform abstractions and uniform utility methods for the Data Access Layer in an application and support wide range of databases and datastores.

2 Java Persistence API

Java has created a specification called as Java Persistent API. It aims towards bringing consistency around accessing different databases. In the last section we discussed that many types of datastores are available in the market. Same is the case with Relational databases. Before JPA we used to use JDBC API to query these relational databases. With JDBC we have to provide native SQL queries. Writing those String representation of SQL was not only tedious but also error-prone. Moreover query syntax may change when you change your database.

You may want your production environment to be based on Oracle, but you need something lightweight at your development or test environment (like postreSQL or H2) . But, if your JDBC has queries really specific to Oracle, your development or tests will fail.

Principle

The JPA is all about creating Objects which can be directly mapped to the Database objects. The application will use JPA specification to push the object or retrieve the object from database. The rest will be taken care by the underlying JPA implementations. This is called as Object Relational Mapping (ORM) there are many JPA implementations like EclipseLink or Hibernate. With ORM, we use an API to query a particular database entity and the result is provided in the form of collection of java objects. Similarly when we want to push data to the database, we just need to populate Java objects and pass them to the API. The underlying ORM implementation is actually responsible for converting these API calls to the native SQL queries.

3 What is Spring Data JPA?

The Spring Data JPA is one of the many Spring Data projects and it aims towards bringing consistency in accessing data for relational datastores. Many people consider Spring Data JPA as a JPA implementation. In reality it is false. Spring Data JPA uses a default JPA Implementation called as Hibernate. The default JPA implementation is configurable and if we wish we can use other implementations as well.

3.1 Spring Data JPA is a add-on

What is Spring Data JPA, if not a JPA Implementation?
Speaking precisely, Spring Data JPA is add-on for JPA. it provides a framework which works together with JPA and provides a complete abstraction over the Data Access Layer in a project.

Spring Data JPA brings in a concept of JPA Repositories a set of Interfaces which defines query methods. The Repository and Entity Bean represent the DAO layer in the application. No need to write native queries anymore. Sometimes we need to write queries or part of queries but those are JQL queries and not native database queries. 

3.2 DAO Abstraction (Repositories)

With Spring Data JPA, we don’t have to write a Data Access Layer or write any SQL statement at all. Based on JPA specification the underlying JPA implementation enables the Entity objects and their metadata mapping. It also enables the entity manager who is responsible for persisting and retrieving entities from database.

The Spring Data JPA, defines Repository interfaces which have methods for storing and finding the entity beans from database. While the interface only defines query methods, spring at runtime, provides proxy implementations for the defined interfaces.

In the background Spring uses the JPA elements like entities, and entity managers but keeps is under the cover and keeps developers free from dealing with them.

3.3 Query Methods

The repositories in Spring Data JPA provides powerful and hassle free means of dealing with data which is called as Query Methods. The name of the methods declared in the repository interfaces are actually converted to low level SQL queries by Spring.

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {

    List<Employee> findAll();

    Optional<Employee> findById(Long employeeId);

    List<Employee> findByFirstNameAndLastName(String firstName, String lastName);

    List<Employee> findByDepartmentNameAndAgeLessThanOrderByDateOfJoiningDesc(String departmentName, int maxAge);

}
  1. The first method will simply be select * from employees
  2. Second method puts a where clause on ’employeeId’ field.
  3. Third one has two where clauses one of first name and other on last name.
  4. More complex query. Which finds list of employees by department name and who are younger than the given date and also sorts the results in descending order date of joining.

We can see the simplicity and the readability of the methods.

3.4 Seamless Integration

Spring Data JPA also helps your DAO layer integrating and interacting with other Spring based components in your application, like accessing property configurations or auto-wiring the repositories into the application service layer.

It also works perfectly with Spring Boot auto-configuration. We only need to provide the datasource details are rest of the things like configuring and using EntityManager.

4 Summary

In this tutorial you understood What is JPA, Spring Data and Spring Data JPA. Below are the important things you learnt today.

  • We are in the world of number of different database storage technologies and each one comes with its own data access API and drivers.
  • Spring Data and its sub-projects provides uniform way of accessing various types of data stores.
  • Java Persistence API (JPA) is a specification provided by Java for APIs accessing various SQL databases.
  • ORM stands for Object Relational Mapping where a Java object is mapped to a database entity and with APIs, we need to work with objects and not with native queries.
  • Spring Data JPA is a sub-project of Spring Data and provides abstraction over the Data Access Layer using Java Persistence API and ORM implementations like Hibernate.

Leave a Reply

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