JPA Specifications


 

Some of variables that come from request can be null. If a variable is null, do not add to query. It's hard to handle when there are bunch of nullable variables in request. Specifications can be solution for this situation.

 

Here is how to do:

Extend repository with: JpaSpecificationExecutor<>

public interface UserRepository extends JpaRepository<User, Long>, 
JpaSpecificationExecutor<User> {
}

 

Add method to service:

public Page<Promotion> getAllByParameters(Integer userId) {
return repository.findAll((Specification<User>) (root, query, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
Optional.ofNullable(userId)
.ifPresent(integer -> predicates.add(criteriaBuilder.equal(root.get("userId"), integer)));
predicates.add(criteriaBuilder.equal(root.get("active"), true));

return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
}, pageable);
}

Return type can be List, you can remove the pageable parameter.

You can do null-check with Optional.ofNullable().


Will be added in this post:

sorting, joining tables, ...

Comments