Search code examples
hibernatespring-bootspring-data-jpaspring-repositories

How to create a select from the database using the spring repositories with a different number of parameters?


I have a filter to search - the user name and the two start and end dates. How can I make select to these fields using the repository?

@Service
public class ResolutionServiceDefault implements ResolutionService {
    @Autowired
    private ResolutionRepository resolutionRepository;

    @Override
    public List<Resolution> findAllFilter(String user, Date start, Date end) {
        if(user!=null)...
        if(start!=null)...
        if(end!=null)...
        //perform a query on the fields that are not null
        return .....;
    }
}

@Repository
public interface ResolutionRepository extends JpaRepository<Resolution, Long> {
    List<Resolution> findAllByStatus(int status);
    List<Resolution> findAll();//String user, Date start, Date end
}

Solution

  • I would use a Specification, something like :

     @Override
     public List<Resolution> findAllFilter(String user, Date start, Date end) {
    
        Specification<Account> specification = new Specification<Account>() {
            public Predicate toPredicate(Root<Account> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
            if(user!=null) {
                predicates.add(root.get("user").equals(user));
            } 
            if(start!=null) {
                predicates.add(root.get("start").equals(start));
            } 
            if(end!=null) {
                predicates.add(root.get("end").equals(end));
            } 
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return repository.findAll(specification);
    }
    

    Your repository will need to look like:

    @Repository
    public interface ResolutionRepository extends JpaRepository<Resolution, Long>, JpaSpecificationExecutor<Resolution> {
    }