Close

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.

Example

Maven Dependencies

pom.xml

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>2.0.6.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.2.13.Final</version>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.196</version>
</dependency>

JPA Entity

@Entity
public class Employee {
  private @Id
  @GeneratedValue
  Long id;
  private String name;
  private String dept;
    .............
}

Implementing CrudRepository

CrudRepository is the central interface for repository abstraction:

package org.springframework.data.repository;
 ...
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

@EnableJpaRepositories
@ComponentScan
@Configuration
public class AppConfig {

  @Bean
  EntityManagerFactory entityManagerFactory() {
      EntityManagerFactory emf =
              Persistence.createEntityManagerFactory("example-unit");
      return emf;
  }

  @Bean
  public PlatformTransactionManager transactionManager() {
      JpaTransactionManager txManager = new JpaTransactionManager();
      txManager.setEntityManagerFactory(entityManagerFactory());
      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

@Component
public class ExampleClient {

  @Autowired
  private EmployeeRepository repo;

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

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

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

      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(employee);

          System.out.println("-- deleting --");
          System.out.println(employee);
          repo.delete(employee);
      }

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

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

  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);
      exampleClient.run();
      EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
      emf.close();
  }
}
 -- 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
                • EmployeeRepository.java
          • resources
            • META-INF

    See Also