JPQL
QueryDSL
EntityManger
또는 @Query
구현체를 통해 JPQL 쿼리를 사용할 수 있다.@Test
public void testEmCreateQuery() {
String qlString = "select u from User u " + //form User -> entity 명
"where u.username = :username";
Member findUser = em.createQuery(qlString, User.class)
.setParameter("username", "teasun")
.getSingleResult();
assertThat(findUser.getUsername()).isEqualTo("teasun");
}
@Qeury
(repository interface)@Query
의 인자값으로 간단하게 쿼리를 작성할 수 있다.
변수 바인딩
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u, u.password AS customField FROM User u WHERE u.username = ?1")
List<User> findByUsernameWithCustomField(String username, Sort sort);
@Query("SELECT u FROM User u WHERE u.username = ?1")
//?1 -> 첫번째 변수(username)가 들어감
List findByUsername(String username, Sort sort);
}
2. :변수명 사용
```java
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u, u.password AS customField FROM User u WHERE u.username = :username")
List<User> findByUsernameWithCustomField(String username, Sort sort);
@Query("SELECT u FROM User u WHERE u.username = :username")
List<User> findByUsername(String username, Sort sort);
}
@PersistenceContext
EntityManager em;
public List<User> selectUserByUsernameAndPassword(String username, String password){
JPAQueryFactory jqf = new JPAQueryFactory(em);
QUser user = QUser.user;
List<Person> userList = jpf
.selectFrom(user) //selectFrom : 어느 테이블에서 조회할지, select 와 from을 나눌 수 있음
.where(person.username.eq(username)
.and(person.password.eq(password))
.fetch();
return userList;
}