NamedParameter
- @Query 에 선언하던 파라미터들을 ?1 등의 체번으로 가리키지 않게 된다.
- :Name 을 사용하며 정의는 @Param 어노테이션에서 한다.
- Mybatis 에서 보았던 @Param 비슷하게 해당 NamedParam 이 Mapper.xml 에서 사용되는 것과 거의 같은 구조를 보이고 있다.
@Param < org.springframework.data.repository.query.Param 으로 NamedParameter 정의
@Query 에서 :Name 의 형식으로 사용
public interface CommentRepository extends JpaRepository<Comment,Long> {
@Query("SELECT c, c.title as cTitle FROM Comment as c WHERE c.title = :title")
List<Comment> findByTitle(@Param("title") String title, Sort sort);
}
@Test
public void testSort(){
Comment comment = new Comment();
comment.setTitle("Spring?");
comment.setComment("Data JPA");
Comment savedComment = commentRepository.save(comment);
List<Comment> sortedComment = commentRepository.findByTitle("Spring?", Sort.by(Sort.Direction.DESC, "title"));
assertThat(sortedComment.size()).isEqualTo(1);
sortedComment.forEach(System.out::println);
}
Hibernate:
select
comment0_.id as col_0_0_,
comment0_.title as col_1_0_,
comment0_.id as id1_0_,
comment0_.comment as comment2_0_,
comment0_.title as title3_0_
from
comment comment0_
where
comment0_.title=?
order by
comment0_.title desc
2020-11-18 20:33:42.053 TRACE 1676 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Spring?]
2020-11-18 20:33:42.063 TRACE 1676 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([id1_0_] : [BIGINT]) - [1]
2020-11-18 20:33:42.064 TRACE 1676 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([col_0_0_] : [BIGINT]) - [1]
2020-11-18 20:33:42.076 TRACE 1676 --- [ main] o.h.type.descriptor.sql.BasicExtractor : extracted value ([col_1_0_] : [VARCHAR]) - [Spring?]
SpEL : Spring Expression Language 를 지원
- #{#entityName} 제공
- 엔티티 이름을 바꿔도 유지보수 상의 이득을 보게 됨
@Entity(name = "Comm")
public class Comment {
...
}
public interface CommentRepository extends JpaRepository<Comment,Long> {
//표현 식 + #entityName
@Query("SELECT c, c.title as cTitle FROM #{#entityName} as c WHERE c.title = :title")
List<Comment> findByTitle(@Param("title") String title, Sort sort);
}
'springframework > Spring Data JPA' 카테고리의 다른 글
Spring Data JPA : Entity Graph (0) | 2020.11.19 |
---|---|
Spring Data JPA : Update 쿼리 (0) | 2020.11.18 |
Spring Data JPA : Sort 시 내부함수 호출 (0) | 2020.11.18 |
Spring Data JPA : 쿼리 메서드 (0) | 2020.11.18 |
Spring Data JPA : Enity 저장 (0) | 2020.11.18 |