NamedQuery란 미리 정의해서 이름을 부여해두고 사용하는 JPQL이다.
NamedQuery는 다음과 같은 특징을 가지고 있다.
@Entity
@NamedQuery(
name = "Member.findByUsername",
query = "select m from Member m where m.username = :username"
)
public class Member {
@Id @GeneratedValue
private Long id;
private String username;
private int age;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TEAM_ID")
private Team team;
}
List<Member> resultList = em.createNamedQuery("Member.findByusername", Member.class)
.setParameter("username", "회원1")
.getResultList();
for (Member member : resultList) {
System.out.println("member = " + member);
}
// 결과
member = Member{id=3, username='회원1', age=0}