Criteria Builder predicate to get all record of specific month in JPA Criteria Query Builder

Viewed 715

Here is my code.

@RequestMapping("/datatable")
@ResponseBody
public DataTablesOutput<Person> listPersons(DataTablesInput input, HttpSession session,
        HttpServletRequest request, @RequestParam Map<String, String> allRequestParams) {
    // create specification
    Specification<Person> specification = new Specification<Person>() {
        @Override
        public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query,
                CriteriaBuilder criteriaBuilder) {
            // define predicates
            List<Predicate> predicates = new ArrayList<Predicate>();
            // PREDICATE TO GET RECORD OF SPECIFIC MONTH FOR EXAMPLE IF I PASS BIRTH MONTH LIKE '05'
            // IT WILL RETURN ALL THE BIRTHDATE RECORD OF 'MAY' MONTH
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
    DataTablesOutput<Person> persons = employeeMasterService.findAll(input, specification);
    return persons;
}

If I pass the month number for example '05'. It should return all the record of 'May' month of database. I am new in criteria query so please help me.

1 Answers

You can use the CriteriaBuilder#function() method.

In Criteria API following method of CriteriaBuilder can be used to execute a database function.

public static Specification<Person> personSpecification(int month) {
      return (Specification<Person>) (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder
              .equal(criteriaBuilder.function("month", Integer.class, root.get("birthday") ), month);
}

If you send month=5, it will return all person born in the 5th month.

Related