Spring

Spring 데이터를 사용한 REST 쿼리 언어 JPA 사양

기록만이살길 2022. 12. 26. 21:44
반응형

1. 개요

이 예제에서는 Spring Data JPA 및 사양을 사용하여 검색/필터 REST API 를 빌드합니다.

JPA Criteria 기반 솔루션을 사용하여 이 시리즈첫 번째 기사 에서 쿼리 언어를 살펴보기 시작했습니다 .

그렇다면 쿼리 언어가 필요한 이유는 무엇입니까? 매우 단순한 필드로 리소스를 검색/필터링하는 것만으로는 너무 복잡한 API에 충분하지 않기 때문입니다. 쿼리 언어는 더 유연 하며 필요한 리소스를 정확하게 필터링할 수 있습니다.

2. 사용자 엔터티

먼저 검색 API에 대한 간단한 사용자 엔터티부터 시작하겠습니다.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String firstName;
    private String lastName;
    private String email;

    private int age;
    
    // standard getters and setters
}

3. 사양 을 사용하여 필터링

이제 문제의 가장 흥미로운 부분인 사용자 지정 Spring Data JPA 사양으로 쿼리하는 부분으로 바로 들어가 보겠습니다 .

사양 인터페이스 를 구현 하는 UserSpecification 을 만들고 실제 쿼리를 구성하기 위해 자체 제약 조건을 전달합니다 .

public class UserSpecification implements Specification<User> {

    private SearchCriteria criteria;

    @Override
    public Predicate toPredicate
      (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
 
        if (criteria.getOperation().equalsIgnoreCase(">")) {
            return builder.greaterThanOrEqualTo(
              root.<String> get(criteria.getKey()), criteria.getValue().toString());
        } 
        else if (criteria.getOperation().equalsIgnoreCase("<")) {
            return builder.lessThanOrEqualTo(
              root.<String> get(criteria.getKey()), criteria.getValue().toString());
        } 
        else if (criteria.getOperation().equalsIgnoreCase(":")) {
            if (root.get(criteria.getKey()).getJavaType() == String.class) {
                return builder.like(
                  root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");
            } else {
                return builder.equal(root.get(criteria.getKey()), criteria.getValue());
            }
        }
        return null;
    }
}

보시다시피 다음 SearchCriteria  클래스 에서 나타내는 몇 가지 간단한 제약 조건을 기반으로 사양 을 만듭니다 .

public class SearchCriteria {
    private String key;
    private String operation;
    private Object value;
}

SearchCriteria 구현 은 제약 조건의 기본 표현을 보유하며 쿼리를 구성할 이 제약 조건을 기반으로 합니다.

  • key : 필드 이름(예: firstName , age 등)
  • operation : 연산자(예: 같음, 보다 작음 등)
  • value : 필드 값(예: john, 25 등)

물론 구현이 단순하고 개선될 수 있습니다. 그러나 우리에게 필요한 강력하고 유연한 작업을 위한 견고한 기반입니다.

4. 사용자 저장소

다음으로 UserRepository 를 살펴보겠습니다 .

우리는 단순히 JpaSpecificationExecutor 를 확장하여 새로운 사양 API를 얻습니다.

public interface UserRepository 
  extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {}

5. 검색 쿼리 테스트

이제 새로운 검색 API를 테스트해 보겠습니다.

먼저 테스트가 실행될 때 준비할 몇 명의 사용자를 생성해 보겠습니다.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class })
@Transactional
@TransactionConfiguration
public class JPASpecificationIntegrationTest {

    @Autowired
    private UserRepository repository;

    private User userJohn;
    private User userTom;

    @Before
    public void init() {
        userJohn = new User();
        userJohn.setFirstName("John");
        userJohn.setLastName("Doe");
        userJohn.setEmail("john@doe.com");
        userJohn.setAge(22);
        repository.save(userJohn);

        userTom = new User();
        userTom.setFirstName("Tom");
        userTom.setLastName("Doe");
        userTom.setEmail("tom@doe.com");
        userTom.setAge(26);
        repository.save(userTom);
    }
}

다음으로 주어진 성 을 가진 사용자를 찾는 방법을 살펴보겠습니다 .

@Test
public void givenLast_whenGettingListOfUsers_thenCorrect() {
    UserSpecification spec = 
      new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
    
    List<User> results = repository.findAll(spec);

    assertThat(userJohn, isIn(results));
    assertThat(userTom, isIn(results));
}

이제 이름과 성이 모두 지정된 사용자를 찾습니다 .

@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
    UserSpecification spec1 = 
      new UserSpecification(new SearchCriteria("firstName", ":", "john"));
    UserSpecification spec2 = 
      new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
    
    List<User> results = repository.findAll(Specification.where(spec1).and(spec2));

    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}

참고: 사양  을 결합 하기 위해 whereand 를 사용했습니다.

다음으로 주어진 성과 최소 연령을 모두 가진 사용자를 찾아보겠습니다 .

@Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
    UserSpecification spec1 = 
      new UserSpecification(new SearchCriteria("age", ">", "25"));
    UserSpecification spec2 = 
      new UserSpecification(new SearchCriteria("lastName", ":", "doe"));

    List<User> results = 
      repository.findAll(Specification.where(spec1).and(spec2));

    assertThat(userTom, isIn(results));
    assertThat(userJohn, not(isIn(results)));
}

이제 실제로 존재하지 않는 사용자검색하는 방법을 살펴보겠습니다 .

@Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
    UserSpecification spec1 = 
      new UserSpecification(new SearchCriteria("firstName", ":", "Adam"));
    UserSpecification spec2 = 
      new UserSpecification(new SearchCriteria("lastName", ":", "Fox"));

    List<User> results = 
      repository.findAll(Specification.where(spec1).and(spec2));

    assertThat(userJohn, not(isIn(results)));
    assertThat(userTom, not(isIn(results)));  
}

마지막으로 이름의 일부만 지정된 User 를 찾습니다 .

@Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
    UserSpecification spec = 
      new UserSpecification(new SearchCriteria("firstName", ":", "jo"));
    
    List<User> results = repository.findAll(spec);

    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}

6. 조합 사양

다음으로 사용자 지정 사양 을 결합하여 여러 제약 조건을 사용하고 여러 기준에 따라 필터링하는 방법을 살펴보겠습니다 .

사양 을 쉽고 유창하게 결합하기 위해 빌더인 UserSpecificationsBuilder 를 구현할 것입니다. 그러나 확인하기 전에 — SpecSearchCriteria — 개체:

public class SpecSearchCriteria {

    private String key;
    private SearchOperation operation;
    private Object value;
    private boolean orPredicate;

    public boolean isOrPredicate() {
        return orPredicate;
    }
}
public class UserSpecificationsBuilder {
    
    private final List<SpecSearchCriteria> params;

    public UserSpecificationsBuilder() {
        params = new ArrayList<>();
    }

    public final UserSpecificationsBuilder with(String key, String operation, Object value, 
      String prefix, String suffix) {
        return with(null, key, operation, value, prefix, suffix);
    }

    public final UserSpecificationsBuilder with(String orPredicate, String key, String operation, 
      Object value, String prefix, String suffix) {
        SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0));
        if (op != null) {
            if (op == SearchOperation.EQUALITY) { // the operation may be complex operation
                boolean startWithAsterisk = prefix != null && 
                  prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX);
                boolean endWithAsterisk = suffix != null && 
                  suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX);

                if (startWithAsterisk && endWithAsterisk) {
                    op = SearchOperation.CONTAINS;
                } else if (startWithAsterisk) {
                    op = SearchOperation.ENDS_WITH;
                } else if (endWithAsterisk) {
                    op = SearchOperation.STARTS_WITH;
                }
            }
            params.add(new SpecSearchCriteria(orPredicate, key, op, value));
        }
        return this;
    }

    public Specification build() {
        if (params.size() == 0)
            return null;

        Specification result = new UserSpecification(params.get(0));
     
        for (int i = 1; i < params.size(); i++) {
            result = params.get(i).isOrPredicate()
              ? Specification.where(result).or(new UserSpecification(params.get(i))) 
              : Specification.where(result).and(new UserSpecification(params.get(i)));
        }
        
        return result;
    }
}

7. 사용자 컨트롤러

마지막으로 이 새로운 지속성 검색/필터 기능을 사용하고 간단한 검색 작업 으로 UserController 를  생성 하여 REST API를 설정해 보겠습니다.

@Controller
public class UserController {

    @Autowired
    private UserRepository repo;

    @RequestMapping(method = RequestMethod.GET, value = "/users")
    @ResponseBody
    public List<User> search(@RequestParam(value = "search") String search) {
        UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
        Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
        Matcher matcher = pattern.matcher(search + ",");
        while (matcher.find()) {
            builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
        }
        
        Specification<User> spec = builder.build();
        return repo.findAll(spec);
    }
}

영어가 아닌 다른 시스템을 지원하기 위해 Pattern 개체를 변경할 수 있습니다.

Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),", Pattern.UNICODE_CHARACTER_CLASS);

다음은 API를 테스트하기 위한 테스트 URL입니다.

http://localhost:8080/users?search=lastName:doe,age>25

응답은 다음과 같습니다.

[{
    "id":2,
    "firstName":"tom",
    "lastName":"doe",
    "email":"tom@doe.com",
    "age":26
}]

패턴 예 에서 검색은 ","로 분할되므로 검색어에 이 문자를 포함할 수 없습니다. 패턴도 공백과 일치하지 않습니다.

쉼표가 포함된 값을 검색하려는 경우 ";"와 같은 다른 구분 기호를 사용할 수 있습니다.

또 다른 옵션은 따옴표 사이의 값을 검색하도록 패턴을 변경한 다음 검색어에서 이를 제거하는 것입니다.

Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\"([^\"]+)\")");

8. 결론

이 문서에서는 강력한 REST 쿼리 언어의 기반이 될 수 있는 간단한 구현에 대해 설명했습니다.

우리는 API를 도메인에서 멀리 유지하고 다른 많은 유형의 작업을 처리할 수 있는 옵션을 갖도록 Spring 데이터 사양을 잘 활용했습니다.

이 문서 의 전체 구현 은 GitHub 프로젝트 에서 찾을 수 있습니다 . 이것은 Maven 기반 프로젝트이므로 그대로 가져오고 실행하기 쉬워야 합니다.

다음 »
Spring Data JPA 및 Querydsl을 사용한 REST 쿼리 언어
« 이전
Spring 및 JPA 기준을 사용한 REST 쿼리 언어
REST footer banner
참고
  • https://docs.spring.io/spring-framework/docs/current/reference/html
  • https://www.baeldung.com/rest-api-search-language-spring-data-specifications
반응형