Bibi's DevLog ๐Ÿค“๐ŸŽ

[Spring] @Query ๋ณธ๋ฌธ

๐Ÿ–ฅ BE ๋ฐฑ์—”๋“œ/Spring ์Šคํ”„๋ง

[Spring] @Query

๋น„๋น„ bibi 2021. 4. 30. 20:00

@Query

public interface CardRepository extends CrudRepository<Card, Long> {
    @Query("select * from card c where not c.status = 'DELETED'")
    List<Card> findByStatusIsNotDeleted();
}
  • @Query() ์ฐธ๊ณ 

    • Spring Data JPA์—์„œ ์ฟผ๋ฆฌ๋ฅผ ์ง์ ‘ ์‚ฌ์šฉํ•ด์•ผ ํ•  ๋•Œ ์‚ฌ์šฉ. ์ธํ„ฐํŽ˜์ด์Šค์— ์ง์ ‘ ๋ฉ”์„œ๋“œ๋ฅผ ์ •์˜ํ•ด ์‚ฌ์šฉํ•œ๋‹ค.
    1. ์›ํ•˜๋Š” ํ˜•์‹์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ์ •์˜

      • (ํ•„์š”ํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ, ๋ฆฌํ„ดํƒ€์ž… ์ง€์ • - ํŠน์ • ํƒ€์ž…์ธ ๊ฒฝ์šฐ ๊ทธ ํƒ€์ž…์„, Collection์ผ ๊ฒฝ์šฐ Set/List/Map์„ ์‚ฌ์šฉ)
    2. ๋ฉ”์†Œ๋“œ์— @Query ์‚ฌ์šฉ

      • *@Query์— ๋“ค์–ด๊ฐˆ ํ…Œ์ด๋ธ”, ์†์„ฑ ๋ช…์€ DB ํ…Œ์ด๋ธ”์ด ์•„๋‹Œ Entityํด๋ž˜์Šค ๊ธฐ์ค€์œผ๋กœ ์ž‘์„ฑํ•ด์•ผ ๋™์ž‘ํ•œ๋‹ค.
    3. @Query์—์„œ ์‚ฌ์šฉํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ๋“ค์€ ์ธํ„ฐํŽ˜์ด์Šค์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์•„์•ผ ํ•œ๋‹ค.

      • ์ธํ„ฐํŽ˜์ด์Šค์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์„ ๋•Œ๋Š” @Param ์–ด๋…ธํ…Œ์ด์…˜์„ ๋ถ™์ด๊ณ , ํŒŒ๋ผ๋ฏธํ„ฐ๋ช…์„ ๊ด„ํ˜ธ ์•ˆ์— ์ž‘์„ฑํ•œ๋‹ค. @Param("")
      • ์ฟผ๋ฆฌ๋ฌธ ๋‚ด๋ถ€์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ๋Š” :parameter ํ˜•์‹์œผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค. (๊ณต๋ฐฑ์ด ์—†์–ด์•ผ ํ•œ๋‹ค)

    ์˜ˆ์‹œ ์ฝ”๋“œ

    public interface FlightRepository extends JpaRepository<Flight, Long> {
    
      @Query("from Flight "
          + "where  departureCity= :departureCity and "
          + "       arrivalCity= :arrivalCity and "
          + "       dateOfDeparture= :dateOfDeparture")
      List<Flight> findFlights (
          @Param("departureCity") String from, 
          @Param("arrivalCity") String to, 
          @Param("dateOfDeparture") Date departureDate
      );
    
    }