728x90
반응형
애플리케이션을 개발하려면 데이터 조회하는 기능은 필수..
쿼리 메소드는 스프링 데이터 JPA 에서 제공하는 핵심 기능 중 하나로
Repository 인터페이스에 간단한 네이밍 룰을 이용하여 메소드를 작성하면 원하는 쿼리를 실행할 수 있다!
find + (엔티티 이름) + By + 변수 이름
find 를 가장 많이 사용하고 엔티티 이름은 생략 가능함.
쿼리 메소드 셈플 및 JPQL snippet
| Keyword | Sample | JPQL snippet |
| And | findByLastnameAndFirstname | where x.lastname = ?1 and x.firstname = ?2 |
| Or | findByLastnameOrFirstname | where x.lastname = ?1 or x.firstname = ?2 |
| Is, Equals | findByFirstname findByFristnameIs findByFirstnameEquals |
where x.firstname = ?1 |
| Between | findByStartDateBetween | where x.startDate between ?1 and ?2 |
| LessThan | findByAgeLessThan | where x.age < ?1 |
| LessThanEqual | findByAgeLessThanEqual | where x.age <= ?1 |
| GreaterThan | findByAgeGreaterThan | where x.age > ?1 |
| GreaterThanEqual | findByAgeGreaterThanEqual | where x.age >= ?1 |
| After | findByStartDateAfter | where x.startDate > ?1 |
| Before | findByStartDateBefore | where x.startDate < ?1 |
| IsNull, Null, IsNotNull | findByAge(Is)Null | where x.age is null |
| NotNull | findByAge(Is)NotNull | where x.age not null |
| Like | findByFirstnameLike | where x.firstname like ?1 |
| NotLike | findByFirstnameNotLike | where x.firstname not like ?1 |
| StartingWith | findByFirstnameStartingWith | where x.firstname like ?1 (parameter bound with appended %) |
| EndingWith | findByFirstnameEndingWith | where x.firstname like ?1 (parameter bound with prepended %) |
| Containing | findByFirstnameContaining | where x.firstname like ?1 (parameter bound wrapped in %) |
| OrderBy | findByAgeOrderByLastnameDesc | where x.age = ?1 order by x.lastname desc |
| Not | findByLastnameNot | where x.lastname <> ?1 |
| In | findByAgeIn(Collection<Age> ages) | where x.age in ?1 |
| Notln | findByAgeNotIn(Collection<Age> ages) | where x.age not in ?1 |
| True | findByActiveTrue() | where x.active = true |
| False | findByActiveFalse() | where x.active = false |
| IgnoreCase | findByRistnameIgnoreCase | where UPPER(x.firstname) = UPPER(?1) |
//쿼리 메소드 예시
//ItemRepository.java
List<Item> findByItemNmOrItemDetail(String itemNm, String itemDetail);
//ItemRepositoryTest.java
@SpringBootTest
@TestPropertySource(locations="classpath:application-test.properties")
class ItemRepositoryTest {
@Test
@DispalyName("or Test")
public void findByItemNmOrItemDetailTest() {
this.createItemList();
//기존에 만들었던 테스트 상품을 만드는 메소드를 실행하여 조회할 대상을 만듬.
List<Item> itemList = itemRepository.findByItemNmOrItemDetail("test1", "detail5");
//test1, detail5 해당 상품을 itemList에 할당.
for(Item item : itemList) {
System.out.println(item.toString());
}
}
}728x90
반응형
'Spring boot' 카테고리의 다른 글
| Thymeleaf(타임리프) (0) | 2023.09.04 |
|---|---|
| Spring DATA JPA (2) | 2023.09.02 |
| @Entity 와 @Repository 설계 (0) | 2023.09.01 |
| JPA(Java Persistence API) (0) | 2023.08.31 |
| Spring boot (0) | 2023.08.28 |