Spring Data JPA - Quick Start Example

[Last Updated: Aug 17, 2018]

This is a kick start example of spring-data-jpa module. This module is a sub project of spring-data (link).

spring-data is an umbrella project that provides repository and object-mapping abstractions. In simple words, it provides a common ground to automatically generate DAO/repositories for us.

There exist multiple sub projects under spring-data (link).

Spring Data Commons (spring-data-commons) - provides core concepts and APIs.

Spring Data JPA (spring-data-jpa) implements spring-data-commons abstractions and generates JPA-based repositories.


Maven Dependencies



JPA Entity

public class Employee {
  private @Id
  Long id;
  private String name;
  private String dept;

Implementing CrudRepository

CrudRepository is the central interface for repository abstraction:

public interface CrudRepository<T, ID> extends Repository<T, ID> {
      <S extends T> S save(S entity);
      <S extends T> Iterable<S> saveAll(Iterable<S> entities);
      Optional<T> findById(ID id);
      boolean existsById(ID id);
      Iterable<T> findAll();
      Iterable<T> findAllById(Iterable<ID> ids);
      long count();
      void deleteById(ID id);
      void delete(T entity);
      void deleteAll(Iterable<? extends T> entities);
      void deleteAll();

The good news is, we don't have to implement any methods. spring-data will use an implementation automatically for us. We just need to declare an interface extending above one. In our example the generic type 'T' would be Employee and 'ID' would be Long.

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

Java Config

public class AppConfig {

  EntityManagerFactory entityManagerFactory() {
      EntityManagerFactory emf =
      return emf;

  public PlatformTransactionManager transactionManager() {
      JpaTransactionManager txManager = new JpaTransactionManager();
      return txManager;

In this quick example, we are keeping the things as simple as possible. Above two beans are necessary for things to work. Also check out our spring-orm tutorials to understand the purpose of above two beans.

Annotation @EnableJpaRepositories is used to enable JPA repositories.

Example Client

public class ExampleClient {

  private EmployeeRepository repo;

  public void run() {
      List<Employee> employees = createEmployees();

      System.out.println(" -- saving employees --");

      System.out.println(" -- finding all employees --");
      Iterable<Employee> all = repo.findAll();

      if (repo.existsById(1L)) {
          System.out.println("-- finding by id --");
          Optional<Employee> employeeOptional = repo.findById(1L);
          Employee employee = employeeOptional.orElseThrow(RuntimeException::new);

          System.out.println("-- deleting --");

      if (repo.existsById(2L)) {
          System.out.println("-- updating --");
          Employee employee2 = repo.findById(2L).orElseThrow(RuntimeException::new);

      System.out.println(" -- finding all employees again --");
      Iterable<Employee> all2 = repo.findAll();

  private List<Employee> createEmployees() {
      return Arrays.asList(
              Employee.create("Diana", "Admin"),
              Employee.create("Mike", "Sale"),
              Employee.create("Rose", "IT")


The main class

public class ExampleMain {

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      ExampleClient exampleClient = context.getBean(ExampleClient.class);;
      EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
 -- saving employees --
[Employee{id=null, name='Diana', dept='Admin'}, Employee{id=null, name='Mike', dept='Sale'}, Employee{id=null, name='Rose', dept='IT'}]
-- finding all employees --
[Employee{id=1, name='Diana', dept='Admin'}, Employee{id=2, name='Mike', dept='Sale'}, Employee{id=3, name='Rose', dept='IT'}]
-- finding by id --
Employee{id=1, name='Diana', dept='Admin'}
-- deleting --
Employee{id=1, name='Diana', dept='Admin'}
-- updating --
Employee{id=2, name='Mike', dept='Sale'}
-- finding all employees again --
[Employee{id=2, name='Mike', dept='IT'}, Employee{id=3, name='Rose', dept='IT'}]

Example Project

Dependencies and Technologies Used:

  • spring-data-jpa 2.0.6.RELEASE: Spring Data module for JPA repositories.
    Uses org.springframework:spring-context version 5.0.5.RELEASE
  • hibernate-core 5.2.13.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • h2 1.4.196: H2 Database Engine.
  • JDK 1.8
  • Maven 3.3.9

Spring Data JPA Quick Start Example Select All Download
  • spring-data-jpa-getting-started
    • src
      • main
        • java
          • com
            • logicbig
              • example
          • resources
            • META-INF

    See Also