[JPA] @Query ์‚ฌ์šฉ

@Query ์‚ฌ์šฉ

@Query๋ฅผ ์‚ฌ์šฉํ•ด์„œ Repository์—์„œ ์ฟผ๋ฆฌ๋ฌธ(DML)์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž.

์–ด๋…ธํ…Œ์ด์…˜

@Modifying

JPA๊ฐ€ ์ง€์›ํ•˜๋Š” Select ๊ตฌ๋ฌธ ์™ธ์— DML(insert, update, delete)๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด์„  @Modifying ์–ด๋…ธํ…Œ์ด์…˜์ด ํ•„์š”ํ•˜๋‹ค.

@Query(value = โ€œ์ฟผ๋ฆฌ๋ฌธโ€, nativeQuery = true)

@Query๋ฅผ ์„ ์–ธํ•œ ๋’ค, value์— ์‚ฌ์šฉํ•  ์ฟผ๋ฆฌ๋ฌธ์„ ์ž…๋ ฅํ•˜๊ณ , nativeQuery๋ฅผ true๋กœ ์„ค์ •ํ•ด์•ผ ํ•œ๋‹ค.

์˜ˆ์‹œ

FeedbackRepository

import com.vividswan.studymate.model.Feedback;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

public interface FeedbackRepository extends JpaRepository<Feedback, Long> {


    @Modifying
    @Query(value = "INSERT INTO feedback(userId, taskId, content, createDate) VALUES(?1, ?2, ?3, now())",nativeQuery = true)
    void createReply(long userId, long taskId, String content);
}

์–ด๋…ธํ…Œ์ด์…˜์„ ์„ ์–ธํ•˜๊ณ , value์— ์›ํ•˜๋Š” ์ฟผ๋ฆฌ๋ฌธ์„ ๋„ฃ์–ด์คฌ๋‹ค.
Insert ๋ฌธ์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.
์ด๋•Œ ? + ๋ฉ”์„œ๋“œ ์ธ์ž ๋ฒˆํ˜ธ๋กœ ์ฟผ๋ฆฌ๋ฌธ ์ž๋ฆฌ์— ๋“ค์–ด๊ฐˆ ๋ฐ์ดํ„ฐ ๊ฐ’์„ ์„ ์–ธํ•  ์ˆ˜ ์žˆ๋‹ค.
์œ„์˜ ์˜ˆ์ œ์—์„ 

  • ?1 => long userId
  • ?2 => long taskId
  • ?3 => String content ๋กœ ๋งž์ถฐ์„œ ์ฟผ๋ฆฌ๋ฌธ์— ๊ฐ’์ด ๋“ค์–ด๊ฐ„๋‹ค.

ํ…Œ์ŠคํŠธ

๊ฐ’์„ ๋„ฃ์–ด๋ณด๊ณ  ์ฝ˜์†” ์ฐฝ์„ ํ™•์ธํ•ด๋ณด์ž.

1

์ž‘์„ฑํ–ˆ๋˜ ์ฟผ๋ฆฌ๋ฌธ์ด ์ ์šฉ๋˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.