Featured Post

Event Sourcing Video from Michael Ploed

Event Sourcing I want to share a great video I found few days ago that describes very well what Event Sourcing is.

Thursday, April 23, 2015

Spring Data Specification Example

In this post i write the java code to make a simple query ( get a User by name) using Spring Data with JPA.

Step1: Create the entity User.java


package com.simonefolinojavablog;

public class User{
   private String id;

   private String name;

Step2: Create the static metamodel (User_.java) for the entity User


package com.simonefolinojavablog;

public class User_ {

  public static volatile SingularAttribute<User, String> id;

  public static volatile SingularAttribute<User, String> name;

Step3: Create the specification to use for the query


package com.simonefolinojavablog;

import org.springframework.data.jpa.domain.Specification;

public class UserSpecifications {

 public static <T extends User> Specification<T> userNameIs(final User user) {
  return new Specification<T>() {
   public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    return cb.equals(root.<String> get(User_.name), user.getName());

Step4: Create the repository for the entity User


package com.simonefolinojavablog;

public interface UserRepository extends PagingAndSortingRepository<User, String>, 
  JpaSpecificationExecutor<User>, JpaRepository<User, String> {


Step5: Use the previous components to build the service method FindByName

ExampleTest .java

import static org.springframework.data.jpa.domain.Specifications.where;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications

public class ExampleTest {

private UserRepository  userRepository;

public void User findByName(User user){

Specification<User> userNameIs= UserSpecifications.<User> userNameIs(user);
       Specifications<User> whereconditions = where(userNameIs);
       return userRepository.findOne(userIdIs);


No comments :

Post a Comment