Thursday, August 17, 2023

Spring Data JPA - Spring Data Tutorial

Though using Spring framework reduces the amount of code and configuration needed to work with any persistence store but you still, generally need to write a DAO interface and a DAO implementation class. Use of Spring Data Repository abstraction over the persistence store significantly reduces the amount of boilerplate code required to implement data access layers for various persistence stores.

With Spring Data you just create an interface extending the framework provided interface (Repository, CrudRepository, JpaRepoitory). Spring framework creates the implementation class automatically, you don't need to write DAO implementation class yourself. In this Spring Data tutorial we'll get to know about the core concepts of data repository, Spring data modules and how to use data repository.

Spring data modules

Spring data is an umbrella project which contains many subprojects that are specific to a given database. Some of the main modules are listed here.

Data Module Description
Spring Data CommonsCore Spring concepts underpinning every Spring Data module
Spring Data JDBCSpring Data repository support for JDBC
Spring Data JPASpring Data repository support for JPA
Spring Data KeyValueMap based repositories and SPIs to easily build a Spring Data module for key-value stores
Spring Data LDAPSpring Data repository support for Spring LDAP
Spring Data MongoDBSpring based, object-document support and repositories for MongoDB
Spring Data RedisEasy configuration and access to Redis from Spring applications
Spring Data RESTExports Spring Data repositories as hypermedia-driven RESTful resources
Spring Data for Apache CassandraEasy configuration and access to Apache Cassandra or large scale, highly available, data-oriented Spring applications

Spring Data Repositories

The central interface in the Spring Data repository abstraction is Repository. It takes the domain class to manage as well as the identifier type of the domain class as type arguments. Repository is a marker interface.

public interface Repository<T, ID> {

}

CrudRepository

CrudRepository interface extends Repository and provides sophisticated CRUD functionality for the entity class that is being managed.

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 deleteAllById(Iterable<? extends ID> ids);
  void deleteAll(Iterable<? extends T> entities);
  void deleteAll();
}

Explanation for some of the methods.

  1. save(S entity)- Saves the given entity.
  2. findById(ID id)- Returns the entity identified by the given ID.
  3. findAll()- Returns all entities.
  4. count()- Returns the number of entities.
  5. delete(T entity)- Deletes the given entity.
  6. existsById(ID id)- Indicates whether an entity with the given ID exists.

PagingAndSortingRepository

PagingAndSortingRepository abstraction adds additional methods to ease paginated access to entities.

public interface PagingAndSortingRepository<T, ID> extends Repository<T, ID> {
  Iterable<T> findAll(Sort sort);
  Page<T> findAll(Pageable pageable);
}

module-specific interfaces

Then there are module specific interfaces also, for example, if you are using JPA then you will use Spring Data JPA dependency and the interface is JpaRepository.

If you are using MongoDB then you will use Spring Data MongoDB dependency and the interface is MongoRepository.

JpaRepository

JpaRepository provides JPA specific extensions like flushing all pending changes to DB and deleting records in batch.

public interface JpaRepository<T, ID> extends ListCrudRepository<T, ID>, ListPagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {

  void flush();

  <S extends T> S saveAndFlush(S entity);

  <S extends T> List<S> saveAllAndFlush(Iterable<S> entities);

  @Deprecated
  default void deleteInBatch(Iterable<T> entities) {
    deleteAllInBatch(entities);
  }

  void deleteAllInBatch(Iterable<T> entities);

  void deleteAllByIdInBatch(Iterable<ID> ids);

  void deleteAllInBatch();

  @Deprecated
  T getOne(ID id);

  @Deprecated
  T getById(ID id);

  T getReferenceById(ID id);

  @Override
  <S extends T> List<S> findAll(Example<S> example);

  @Override
  <S extends T> List<S> findAll(Example<S> example, Sort sort);
}
Spring Data

How to use Spring Data Repository

In order to use Spring data repository, you need to follow the following steps. Note that Spring Data JPA is used here.

For complete example using Spring Boot and Spring Data JPA check this post- Spring Boot + Data JPA + MySQL REST API CRUD Example

1. Adding dependency- If you are using Spring boot and you want to use Spring data JPA then you need to add dependency for spring-boot-starter-data-jpa.

If you are using Spring framework then you need to add dependency for spring-data-jpa.

2. Creating Repository- For example if there is an entity class Customer where the field annotated with @Id is of type Long.

@Entity
@Table(name="customer")
public class Customer {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String name;
	private int age;
	private String city;
}

Then you need to declare an interface extending Repository or one of its sub-interfaces and type it to the domain class and ID type that it should handle.

public interface CustomerRepository extends JpaRepository<Customer, Long>{

}

If you don't need the full functionality provided by JpaRepository you can also extend the CrudRepository.

That's all you need to provide; Spring framework automatically generates the implementation class implementing all the methods available in JpaRepository interface.

You can also provide other methods in your interface and Spring framework provides implementation for those methods too, deriving it by the method name. For example, if you want to find customer by city.

public interface CustomerRepository extends JpaRepository<Customer, Long>{
  List<Customer> findByCity(String city);
} 

3. Enabling Spring Data JPA repositories support- If you are using Spring Boot then you don't need to do any thing to enable data repository support. Seeing spring-data-jpa jar in project's class path Spring Boot automatically configures the application to use Spring data jpa repository.

With Spring framework you need to add @EnableJpaRepositories annotation if you are using Java configuration.

@Configuration
@EnableJpaRepositories("com.netjstech.datademo.dao.repository")
@EnableTransactionManagement
public class JPAConfig {
  ...
  ...
}

With XML configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <jpa:repositories base-package=" com.netjstech.datademo.dao.repository " />

</beans>

4. Using the repository- Inject the repository in the class where you need to use it and start calling the methods. Implementation of these methods will be there!

@Service
public class CustomerService {
  @Autowired
  private CustomerRepository repository;

  public Customer getCustomerById(long id) {
    return repository.findById(id).get();
  }

  …
  …

}

That's all for this topic Spring Data JPA - Spring Data Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Boot + Data JPA + MySQL REST API CRUD Example
  2. Spring JdbcTemplate Select Query Example
  3. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  4. Spring Transaction Management Example - @Transactional Annotation and JDBC

You may also like-

  1. Spring Boot Microservice - Service Registration and Discovery With Eureka
  2. Circular Dependency in Spring Framework
  3. @FunctionalInterface Annotation in Java
  4. Java join() Method - Joining Strings
  5. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
  6. AtomicInteger in Java With Examples

Spring Boot + Data JPA + MySQL REST API CRUD Example

In this post Spring Data tutorial we got to know about Spring Data and how to use it. In this tutorial we'll create a Spring Boot REST API crud application using Spring Data JPA and MySQL database.