Specification을 통해 Filter 하기

AwardSpecs.java

package com.innogrid.www.model.specs;

import org.springframework.data.jpa.domain.Specification;

import com.innogrid.www.model.AwardEntity;

import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AwardSpecs {

    public enum SearchKey {
        AWARDTYPE("type"),
        AWARDNAME("name"),                   // 인증/수상/특허 이름
        AWARDCA("ca"),                       // 인증처
        AWARDNUM("num"),                     // 특허번호
        AWARDDESCRIPTION("description");     // 수상 내용

        private final String value;

        SearchKey(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }
    public static Specification<AwardEntity> searchWith(Map<SearchKey, Object> searchKeyword) {
        return (Specification<AwardEntity>) ((root, query, builder) -> {
            List<Predicate> predicate = getPredicateWithKeyword(searchKeyword, root, builder);
            return builder.and(predicate.toArray(new Predicate[0]));
        });
    }
    
    private static List<Predicate> getPredicateWithKeyword(Map<SearchKey, Object> searchKeyword, Root<AwardEntity> root, CriteriaBuilder builder) {
        List<Predicate> predicate = new ArrayList<>();
        for (SearchKey key : searchKeyword.keySet()) {
            switch (key) {
                default:
                    predicate.add(builder.equal(
                            root.get(key.value),searchKeyword.get(key)
                    ));
                    break;
            }
        }
        return predicate;
    }
}

AwardController.java

    @GetMapping("/awards")
    @Operation(summary = "인증/수상/특허 목록", description = "인증/수상/특허 목록을 조회합니다.")
    public ResponseEntity<?> findAllAwards(
            @RequestParam(required = false) Map<String, Object> searchRequest,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "id,desc") String[] sort) {

        log.info("retrieve all awards controller...!");

        if(page <= 0) {
            return new ResponseEntity<>(ErrorResponse.of(ErrorCode.PAGE_INT_ERROR), HttpStatus.BAD_REQUEST);
        }        

        Pageable pageable = PageRequest.of(page-1, size, Sort.by(Common.getOrder(sort)));


        Map<SearchKey, Object> searchKeys = new HashMap<>();
        for (String key : searchRequest.keySet()) {
            searchKeys.put(SearchKey.valueOf(key.toUpperCase()), searchRequest.get(key));
        }

        Page<AwardEntity> awardEntity = null;

        if(searchKeys.isEmpty()) {
            awardEntity = awardRepository.findAll(pageable);
        } else {
            awardEntity = awardRepository.findAll(AwardSpecs.searchWith(searchKeys), pageable);
        }

        return new ResponseEntity<>(awardEntity, new HttpHeaders(), HttpStatus.OK);
    }
You've successfully subscribed to taking
Great! Next, complete checkout to get full access to all premium content.
Error! Could not sign up. invalid link.
Welcome back! You've successfully signed in.
Error! Could not sign in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.