Suggested Pages

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

User.java

package com.simonefolinojavablog;

@Entity
public class User{
 
   @Id
   private String id;

   @Column
   private String name;
    ...
}   

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

User_.java

package com.simonefolinojavablog;

@StaticMetamodel(User.class)
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

UserSpecifications.java

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>() {
   @Override
   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

UserRepository.java

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

Suggested Pages