Spring Data Tutorial

Spring Data provides abstraction on top of the persistence store you are using (JPA, NoSQL, JDBC etc.) you can significantly reduce the amount of boilerplate code required to implement data access layers for those persistence stores.
As a developer you just need to write your repository interfaces, including custom finder methods, and Spring will provide the implementation for those data access methods automatically. In this Spring Data tutorial we’ll go through the available modules in Spring Data, available repositories and how to use Spring Data repositories.

Spring Data Modules

Spring Data has many modules corresponding to supported persistence stores. Spring Data Commons is the common module for every Spring Data module. This is the module where CrudRepository and PagingAndSortingRepository interfaces reside.

Some of the other data modules are-

  • Spring Data JDBC- Spring Data repository support for JDBC.
  • Spring Data JPA- Spring Data repository support for JPA.
  • Spring Data LDAP- Spring Data repository support for Spring LDAP.
  • Spring Data MongoDB- Spring based, object-document support and repositories for MongoDB.
  • Spring Data Redis- Easy configuration and access to Redis from Spring applications.
  • Spring Data REST- Exports Spring Data repositories as hypermedia-driven RESTful resources.
  • Spring Data for Apache Cassandra- Easy configuration and access to Apache Cassandra or large scale, highly available, data oriented Spring applications.

Spring Data Repository

The central interface in the Spring Data repository abstraction is Repository.

public interface Repository<T, ID> {

}

Repository is a marker interface and it takes the domain class to manage as well as the ID type of the domain class as type arguments.

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

On top of the CrudRepository, there is a PagingAndSortingRepository abstraction that adds additional methods to ease paginated access to entities.

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

Spring Data

Steps for using Spring Data

Steps for using Spring data repositories are as follows, repository used here for reference is Spring Data JPA repository. See complete example using Spring Data JAP in this post- Spring Data JPA Example

1. Declare an interface extending Repository or one of its subinterfaces and type it to the domain class and ID type that it should handle. For example if you have an entity class Employee with employee ID having the type int.

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
	List<Employee> findByLastName(String lastName);
}

Apart from the query methods inherited from CrudRepository you can also write your own custom query methods too.

2. Set up Spring to create proxy instances for the interface. If you are using JavaConfig

@Configuration
@EnableJpaRepositories("com.knpcode.springproject.dao")
@EnableTransactionManagement
public class JPAConfig {
	...
	...
}

@EnableJpaRepositories annotation enables the JPA repositories. Package to scan for the repositories is provided as a value with this annotation.
@EnableTransactionManagement annotation enables Spring’s annotation-driven transaction management capability.

If you are using XML configuration then the configuration for enabling JPA repositories is-

<jpa:repositories base-package="com.knpcode.springproject.dao"/>

3. Inject the repository instance and use it.

@Service
public class EmployeeService {
	@Autowired
	private EmployeeRepository repository;
	
	public Employee getEmployeeById(int id) {
		return repository.findById(id).get();
	}
	
	public List<Employee> getAllEmployees(){
		return (List<Employee>) repository.findAll();
	}
	..
	..
}

Options for query creations in Spring Data

1. Queries for the methods defined in the Repository interfaces can be created automatically by deriving query from the query method name. The general approach is to remove a given set of well known prefixes (i.e. find…By, query…By, count…By etc.) from the method name and parse the rest of the method. That is applicable to both methods you get by extending Repository (or sub-interface) interface and custom methods that follow the same convention of naming the methods.

2. You can also declare query by using annotation. For Spring Data JPA you can use @NamedQuery ( element in case of XML configuration) to define a query in entity class or annotate your query method with @Query with in the Repository interface. For Spring Data Mongo and Spring Data Neo4J too @Query annotation is available to define query.

To know more about query methods in Spring Data, check this post- Spring Data Query Methods

Related Posts

That’s all for the topic Spring Data Tutorial. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.