javaspringhibernatespring-data-jpajpamodelgen

Should Predicates of Spring Specification be static?


Should a Predicate of springs Specification be static or nonstatic?

The default implementation would be similar as follows:

public static Specification<Customer> byCustomerName(String name) {
    return new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.equal(root.get(Customer_.name), name);
        }
    };
}

But this could also be refactored to:

private static final CUSTOMER_SPEC = return new Specification<Customer>() {
    @Override
    public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        return cb.equal(root.get(Customer_.name), name);
    }
};

public static Specification<Customer> byCustomerName(String name) {
    return CUSTOMER_SPEC;
}

What should be prefered? Are Specifications threadsafe and can be used this way?


Solution

  • You're refactored code wouldn't even compile. There's a superfluous return, CUSTOMER_SPEC doesn't have a type, and you're referring to a name variable that doesn't exist in the scope.

    I think you're overthinking the issue here and are in the process of micro-optimizing. Keeping the Specification in a static factory method should be fine.