sm 기술 블로그

[스프링부트] Query 사용 (JPA) 본문

스프링부트

[스프링부트] Query 사용 (JPA)

sm_hope 2022. 8. 11. 23:05

1. 자동으로 생성

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,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.firstame) = UPPER(?1)

다음과 같은 키워드를 리포지터리에 메소드를 정의해주면 쿼리문을 자동으로 사용 할 수 있다.

2. Query를 직접 써서 직접 메소드를 만드는 방법

1) 쿼리를 직접 쓰는 경우는 From table 별칭을 Select문안에 넣어야 한다. (안그러면 오류 발생)

	@Query("SELECT u FROM User u WHERE u.status = 1") 
	Optional<User> findIdOneUser();

2) DB에 쓰는 것처럼 직접 쿼리를 작성하는 방식

	@Query(value = "SELECT * FROM USERS u WHERE u.status = 1",   nativeQuery = true)
	Optional<User> findIdOneUser();

이 방법 또한 별칭을 사용해야한다.

 

3. Parameter를 통해 @Query에 그 Parameter가 넣어지는 방식

1) ?를 통한경우 parameter의 위치에 따른 숫자를 넣어주면 된다.

        @Query("select u from User u where u.emailAddress = ?1")  
        User findByEmailAddress(String emailAddress);

2) 파라미터의 이름으로 검색하는 경우

@Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")  
User findByLastnameOrFirstname(@Param("lastname") String lastname, @Param("firstname") String firstname);   

@Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")  
User findByLastnameOrFirstname(String lastname, String firstname); //이렇게도 사용 가능하다.
Comments