method 이름으로 db queries를 생성하는 법을 배워보자
2가지 조건을 만족하는 search function을 구현해보겠습니다.
1. 검색 단어(term)를 포함하는 title or description을 갖는 todo entries를 return
2. 대소문자 구별x
다음 규칙에 따라 Query Methods를 생성한다.
Example 1: If we want to create a query method that returns the todo entry whose id is given as a method parameter, we have to add one of the following query methods to our repository interface:
(o)public Todo findById(Long id);
(o!!)public Optional<Todo,> findById(Long id);
Example 2: If we want to create a query method that returns todo entries whose title or description is given as a method parameter, we have to add the following query method to our repository interface:
(X)public List<Todo,> findByTitleOrDescription(String term);
(O)public List<Todo,> findByTitleOrDescription(String title,String description);
Example 3: If we want to create a query method that returns the number of todo entries whose title is given as a method parameter, we have to add the following query method to our repository interface:
public long countByTitle(String title);
Example 4: If we want to return the distinct todo entries whose title is given as a method parameter, we have to add the following query method to our repository interface:
public List<Todo,> findDistinctByTitle(String title);
Example 5: If we want to to return the first 3 todo entries whose title is given as a method parameter, we have to add one of the following query methods to our repository interface:
(X)public List<Todo.> findFirst3ByTitle(String title);
public List<Todo.> findFirst3ByTitleOrderByTitleAsc(String title);
public List<Todo.> findTop3ByTitleOrderByTitleAsc(String title);
term을 포함하는 description 조건을 query로 구현하기 위해
property expression 으로 Description
keyword는 Contains 를 method name에 더한다.
조건1이 true이거나 조건2가 true일때 반환하게 하려면 Or을 method name에 더한다.
Title을 포함하는 query를 생성하고 앞의 조건과 Or로 연결한다.
case 구별을 하지 않고 검색을 하기 위해 AllIgnoreCase를 method name 뒤에 붙인다.
간단한 쿼리는 빨리 만들 수 있고, method 이름으로 검색 condition과 value를 알 수 있다. This query generation strategy has the following weaknesses:
가독성 좋게 하기위해 1개 혹은 2개일때 사용한다.