1. @query 이용
Java Persistence Query Language 인 JPQL이용
Repository method에 @Query Annotation을 사용해서 위의 과정을 SpringDataJPA에 위임
파라미터가 3개 이상이 되거나 order by 절 등을 사용해서 쿼리가 복잡해지면 메서드명이 엄청나게 늘어나 가독성을 저하될때 사용
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
}
2. query method 이용
메서드를 만들어 쓰는 방식을 통해서 서비스단에서 그 메서드를 이용하면, 스스로 쿼리를 생성하여 작동
Keyword | Sample | JPQL snippet |
Distinct | findDistinctByLastnameAndFirstname | select distinct … where x.lastname = ?1 and x.firstname = ?2 |
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is, Equals | findByFirstname,findByFirstnameIs,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 | findByAge(Is)Null | … where x.age is null |
IsNotNull, 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 |
NotIn | findByAgeNotIn(Collection<Age> ages) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstname) = UPPER(?1) |
3. 주의사항
필요한 부분만 꺼내쓰는 것이 중요
성능이슈)
- Hibernate 캐시에 복사본 저장
- 불필요한 컬럼 조회
- OneToOne에서의 N+1 쿼리
'TIL' 카테고리의 다른 글
[TIL] 20240305 JPA 페이징 기능 (0) | 2024.03.05 |
---|---|
[TIL] 20240304 JPA 1차캐시 / 2차캐시 (0) | 2024.03.04 |
[TIL] 20240221 Junit Mock 객체 / Stubbing (0) | 2024.02.21 |
[TIL] Spring AOP (0) | 2024.02.19 |
[TIL] 데이터베이스 식별/비식별 관계 (0) | 2024.02.07 |