Spring data JPA and parameters that can be null

后端 未结 6 1895
不知归路
不知归路 2020-12-03 09:45

My understanding is, that with Spring data JPA I cannot have a query method to fetch all rows where a column equals a given non-null method parameter and use the same method

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 10:30

    While this has been answered and the accepted answer is relevant to the current question but there is another way to handle your null parameters in a JpaRespository. Posting this here as this can be leveraged when someone wants to query by ignoring fields when null and have dynamic query built. The below code sample should demonstrate the same

    public class User{
      private String firstName;
      private String lastName;
    }
    
    import javax.persistence.criteria.Predicate;
    import org.springframework.data.jpa.domain.Specification;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository{
    
      public Page findAll(Specification user,Pageable page);
    
      public default Page findAll(User user,Pageable page){
        return findAll(search(user),page);
      }
    
      static Specification search(User entity) {
        return (root, cq, cb) -> {
          //To ensure we start with a predicate
          Predicate predicate = cb.isTrue(cb.literal(true));
          if(entity.getFirstName() != null && !entity.getFirstName().isBlank()) {
            Predicate _predicate = cb.like(cb.lower(root.get("firstName")), "%"+entity.getFirstName().toLowerCase()+"%");
            predicate = cb.and(predicate,_predicate);
          }
          if(entity.getLastName() != null && !entity.getLastName().isBlank()) {
            Predicate _predicate = cb.like(cb.lower(root.get("lastName")), "%"+entity.getLastName().toLowerCase()+"%");
            predicate = cb.and(predicate,_predicate);
          }
          return predicate;
        }
      }
    }
    

提交回复
热议问题