Spring Data - Part 1: Commons - codecentric AG Blog

:

One goal of the Spring Data project is to provide a common API for accessing both NoSQL datastores and relational databases. Spring Data serves as an umbrella project which offers general solutions – like pagination in large result sets – and consists of several sub projects for different kinds of persistence frameworks.

Within this blog post series I’d like to introduce certain aspects of some of these Spring Data projects. I will start with

Spring Data Commons

The Spring Data Commons project provides basic implementations and interfaces to the other Data projects. No matter what kind of data store you use, you will typically have to

  • perform CRUD (create, read, update, delete) operations
  • sort your data
  • paginate your data

All these aspects are covered with Spring Data Commons through a common API.

Let’s have a look at the most important package org.springframework.data.repository:

The interface Repository is just an empty marker interface. CrudRepository is a lot more interesting: it defines our common CRUD operations along with other useful methods. PagingAndSortingRepository provides common finder methods with support for sorting and paging. All these interfaces support a type safe usage of the persistent entity and the primary key.

In our examples, User will be the persistent domain object which has a primary key of type String.

Sorting

Our user repository is defined like this …

public interface UserRepository extends PagingAndSortingRepository<User, String> {
}

public interface UserRepository extends PagingAndSortingRepository<User, String> { }

… and can be used to find all records and sort the results by id and fullName using different sort directions:

@Autowired UserRepository userRepo;
...
public Iterable<User> getSortedUsers() {
	return userRepo.findAll( new Sort(
		 new Sort.Order(Sort.Direction.ASC, "id"),
		 new Sort.Order(Sort.Direction.DESC, "fullName")
		 )
	);
}

@Autowired UserRepository userRepo; ... public Iterable<User> getSortedUsers() { return userRepo.findAll( new Sort( new Sort.Order(Sort.Direction.ASC, "id"), new Sort.Order(Sort.Direction.DESC, "fullName") ) ); }

Pagination

Paging is very easy:

Page<User> page = userRepo.findAll( new PageRequest(2, 20) );
List<User> users = page.getContent();	 
...

Page<User> page = userRepo.findAll( new PageRequest(2, 20) ); List<User> users = page.getContent(); ...

Here, we are using a page size of 20 and request the 2nd page. A Page objects provides you with the data for the requested page as well as additional information like total result count, page index and some more.

What’s next?

Upcoming blog posts will cover the Spring Data projects like Spring Data JPA and Spring Data MongoDB. We’ll have a look at the basic configurations of the projects, their specific APIs and provide much more example code.

Persist you must, Master Yoda says.