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/

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
35 [EMF] EMF Tutorial EMF 튜터리얼 file 졸리운_곰 2023.08.23 283
34 Eclipse RAP Tutorial for Beginners - Workbench Application (OLD) file 졸리운_곰 2021.01.30 323
33 Learn Eclipse GMF in 15 minutes file 졸리운_곰 2019.11.27 253
32 [Eclipse] GEF entry series (10, an implementation of the form) file 졸리운_곰 2019.11.25 212
31 GEF Programmer Guide 번역 졸리운_곰 2019.11.25 227
30 Learn Eclipse GMF in 15 minutes file 졸리운_곰 2019.11.20 224
29 RCP 에디터 정리 졸리운_곰 2019.11.20 333
28 다른 그림과 관련하여 GEF 편집기 레이아웃에서 그림의 위치 제한 조건을 동적으로 계산 Dynamically calculating the position constraints for a figure in a GEF editor layout in relation to another figure file 졸리운_곰 2019.11.20 277
27 RCP 등에서 .mf 파일로 다른 프로젝트 익스포트 포함시 라이브러리(메소드)를 찾지 못할 때, Eclipse RCP - cant resolve importing libraries in final build file 졸리운_곰 2019.10.15 410
26 ESE2006-EclipseModelingSymposium15_GMF.pdf file 졸리운_곰 2019.09.21 302
25 GMF_Creation_Review.pdf file 졸리운_곰 2019.09.21 366
24 Eclipse EMF and GMF Tutorial file 졸리운_곰 2019.09.21 222
23 GMF Tutorial/ko file 졸리운_곰 2019.09.20 347
22 Model Driven Architecture approach to domain of graphical editors file 졸리운_곰 2019.09.20 268
21 Single_Sourcing_RAP_RCP_en.pdf file 졸리운_곰 2019.05.15 311
20 Rich client platform 설명 및 배우기 참고 졸리운_곰 2019.05.15 309
19 Rich Ajax Platform, Part 1: 소개 file 졸리운_곰 2019.05.15 320
18 또 하나의 크로스 플랫폼: Eclipse RAP file 졸리운_곰 2019.05.15 319
17 Eclipse 4 RCP 튜토리얼(완료) file 졸리운_곰 2019.05.14 977
16 Updating UI in Eclipse RCP 졸리운_곰 2015.11.07 408
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED