Spring Data JPA Tutorial: Creating Database Queries From Method Names

 

This blog post describes how we can create query methods by using the query generation from the method name strategy.

We will also implement a simple search function that has two requirements:

  1. It must return todo entries whose title or description contains the given search term.
  2. The search must be case insensitive.

Let’s get started.Creating Query Methods

The query generation from the method name is a query generation strategy where the invoked query is derived from the name of the query method.

We can create query methods that use this strategy by following these rules:

  • The name of our query method must start with one of the following prefixes: find…Byread…Byquery…Bycount…By, and get…By.
  • If we want to limit the number of returned query results, we can add the First or the Top keyword before the first By word. If we want to get more than one result, we have to append the optional numeric value to the First and the Top keywords. For example, findTopByfindTop1ByfindFirstBy, and findFirst1By all return the first entity that matches with the specified search criteria.
  • If we want to select unique results, we have to add the Distinct keyword before the first By word. For example, findTitleDistinctBy or findDistinctTitleBy means that we want to select all unique titles that are found from the database.
  • We must add the search criteria of our query method after the first By word. We can specify the search criteria by combining property expressions with the supported keywords.
  • If our query method specifies x search conditions, we must add x method parameters to it. In other words, the number of method parameters must be equal than the number of search conditions. Also, the method parameters must be given in the same order than the search conditions.
The following examples demonstrate how we can create simple query methods by using the query generation from the method name strategy:

 

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.data.repository.Repository;
 
import java.util.Optional;
 
interface TodoRepository extends Repository<Todo, Long> {
 
    /**
     * Returns the found todo entry by using its id as search
     * criteria. If no todo entry is found, this method
     * returns null.
     */
    public Todo findById(Long id);
 
    /**
     * Returns an Optional which contains the found todo
     * entry by using its id as search criteria. If no to entry
     * is found, this method returns an empty Optional.
     */
    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:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.data.repository.Repository;
 
import java.util.List;
 
interface TodoRepository extends Repository<Todo, Long> {
 
    /**
     * Returns the found todo entry whose title or description is given
     * as a method parameter. If no todo entry is found, this method
     * returns an empty list.
     */
    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:

1
2
3
4
5
6
7
8
9
10
import org.springframework.data.repository.Repository;
 
interface TodoRepository extends Repository<Todo, Long> {
 
    /**
     * Returns the number of todo entry whose title is given
     * as a method parameter.
     */
    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:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.data.repository.Repository;
 
import java.util.List;
 
interface TodoRepository extends Repository<Todo, Long> {
 
    /**
     * Returns the distinct todo entries whose title is given
     * as a method parameter. If no todo entries is found, this
     * method returns an empty list.
     */
    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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.data.repository.Repository;
 
import java.util.List;
 
interface TodoRepository extends Repository<Todo, Long> {
 
    /**
     * Returns the first three todo entries whose title is given
     * as a method parameter. If no todo entries is found, this
     * method returns an empty list.
     */
    public List<Todo> findFirst3ByTitleOrderByTitleAsc(String title);
 
    /**
     * Returns the first three todo entries whose title is given
     * as a method parameter. If no todo entries is found, this
     * method returns an empty list.
     */
    public List<Todo> findTop3ByTitleOrderByTitleAsc(String title);
}
 

Let’s move on and create the query method that fulfils the requirements of our search function.

Implementing the Search Function

We can implement the search function by following these steps:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

  1. Create a query method whose name starts with the prefix findBy.
  2. Ensure that the query method returns todo entries whose description contains the given search term. We can do this by appending the property expression: Description and the keyword: Containsto the method name.
  3. Configure the query method to return the information of a todo entry if the previous (2) or the next (4) search condition is true. We can do this by appending the keyword: Or to the method name.
  4. Ensure that the query method returns todo entries whose title contains the given search term. We can do this by appending the property expression: Title and the keyword: Contains to the method name.
  5. Ensure that the search is case insensitive. We can do this by appending the keyword: AllIgnoreCase to the method name.
  6. Add two method parameters to the query method:
    1. Spring Data JPA uses the descriptionPart method parameter when it ensures that the description of the returned todo entry contains the given search term.
    2. Spring Data JPA uses the titlePart method parameter when it ensures that the title of the returned todo entry contains the given search term.
  7. Set the type of the returned object to List<Todo>.

The source code of our repository interface looks as follows:

1
2
3
4
5
6
7
8
9
10
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
 
import java.util.List;
 
interface TodoRepository extends Repository<Todo, Long> {
 
    List<Todo> findByDescriptionContainsOrTitleContainsAllIgnoreCase(String descriptionPart,
                                                                     String titlePart);
}

Let’s move on and find out when we should create our query methods by using the query generation from the method name strategy.

When Should We Use the Query Generation From the Method Name Strategy?

This query generation strategy has the following benefits:

  • Creating simple queries is fast.
  • The method name of our query method describes the selected value(s) and the used search condition(s).

This query generation strategy has the following weaknesses:

  • The features of the method name parser determine what kind of queries we can create. If the method name parser doesn’t support the required keyword, we cannot use this strategy.
  • The method names of complex query methods are long and ugly.
  • There is no support for dynamic queries.

When we think about the pros and cons of this strategy and take a second look at our examples, it becomes clear that the length of our query method name determines whether or not we should use this strategy.

I am not a big fan of “super long” method names because they become unreadable very fast. If we compare the method name: findById with the method name: findByDescriptionContainsOrTitleContainsAllIgnoreCase, we notice that first one is very easy to read. The second method name is not nearly as easy to read as the first one, but it is not impossible to read either (yet). It is a borderline case.

Because I want to write code that is easy to read, I think that we should use this strategy only when we are creating simple queries that have only one or two search conditions.

Let’s move on and summarize what we learned from this blog post.Summary

This blog post has taught us the following things:

  • If we want to use the query generation by method name strategy, the name of our query method must start with a special prefix.
  • We can select unique results by using the Distinct keyword.
  • We can limit the number of returned query results by using either the Top or the First keyword.
  • We can create search conditions by using property expressions and the keywords supported by Spring Data JPA.
  • We should use the query generation from the method name strategy only when our query is simple and has only one or two search conditions.

 

 

[출처] https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-from-method-names/

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
38 Spring Batch 간단 정리 Sprong Batch 기초를 알아보자 file 졸리운_곰 2020.10.13 198
37 Spring Batch - ItemReader, ItemWriter, ItemProcessor 졸리운_곰 2020.10.13 370
36 spring batch» Spring Batch Tasklet Example file 졸리운_곰 2020.10.12 198
35 Spring Batch Example 2 - 간단한 Job만들기 file 졸리운_곰 2020.10.12 151
34 Spring batch Job 설정과 실행하기 file 졸리운_곰 2020.10.12 206
33 [Spring Batch] Configuring and Running a Job file 졸리운_곰 2020.10.12 121
32 [스프링] 스프링 배치 기본 개념 file 졸리운_곰 2019.12.24 244
31 Spring Batch 개념 정리 file 졸리운_곰 2019.12.24 257
30 스프링 배치 개발가이드 졸리운_곰 2019.12.24 321
29 Quartz + Spring Batch 조합! Quartz Scheduler 와 Spring Batch 의 궁합과 조합을 정리. file 졸리운_곰 2019.12.24 882
28 Spring Batch 간단 정리 file 졸리운_곰 2019.12.24 421
27 spring batch 소개 file 졸리운_곰 2019.12.24 208
26 Spring Batch - 소개 file 졸리운_곰 2019.12.24 207
25 Spring Batch Multithreading Example file 졸리운_곰 2019.01.31 285
24 Spring batch를 Parallel로 돌려보자 졸리운_곰 2019.01.31 399
23 Spring MVC 주요 애노테이션(Annotation)정리 file 졸리운_곰 2018.12.29 268
22 스프링/스프링부트 애노테이션(Annotation) 정리 졸리운_곰 2018.12.29 385
21 Spring Framework - annotation 정리 #1 졸리운_곰 2018.12.29 321
20 [Spring] Annotation 정리 졸리운_곰 2018.12.29 272
19 Maven 기초 사용법 졸리운_곰 2018.04.15 322
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED