포스트

[TIL] Spring Basics - Query Methods

This is a TIL that summarizes Spring Data JPA's Query Methods and method name-based query creation method.

한국어 원문은 여기에서 볼 수 있습니다.
[TIL] Spring Basics - Query Methods

What to do today

What I studied

Query Methods

Query Methods
Spring Data JPA provides the Query Methods function that can generate SQL with method names.
  • In the JpaRepository interface, you can declare it using the SQL method name you want to request from the table mapped to that interface.
  • When the SimpleJpaRepository class is created, all methods of the directly declared JpaRepository interface are automatically implemented as above.
  • The method of the JpaRepository interface, that is, the Query Method, is implemented in SimpleJpaRepository by analyzing the method name when the developer declares the method in accordance with the already defined rules. ex) findAllByOrderByModifiedAtDesc: The method name is ModifiedAt in the Memo table, that is, you can create a method that executes SQL to retrieve the entire data in descending order based on the modification time. ex) List<Memo> findAllByUsername(String username);: When the Query Method is declared like this, the value must be passed to ByUsername, so declare the type and variable name of the value in the parameter.
    • In other words, the Query Method can dynamically receive and process the values required for SQL through the method’s parameters.
  • Application of Query Methods
    • Modified so that the latest notes appear at the top
      1
      2
      3
      4
      5
      
      // MemoService
      public List<MemoResponseDto> getMemos() {
      // DB 조회
      return memoRepository.findAllByOrderByModifiedAtDesc().stream().map(MemoResponseDto::new).toList();
      }
      

Problems & Errors

What to do tomorrow