프로젝션이란 SELECT 절에 조회할 대상을 지정하는 것이다.
프로젝션 대상으로는 엔티티
, 임베디드 타입
, 스칼라 타입
이 있다.
이 3가지에 대해 알아보겠다.
Member member = new Member();
member.setUsername("member1");
member.setAge(10);
em.persist(member);
em.flush();
em.clear();
List<Member> result = em.createQuery("select m from Member m", Member.class)
.getResultList();
Member findMember = result.get(0);
// (1)
findMember.setAge(20);
엔티티 프로젝션의 경우 쿼리의 결과로 가져와지는 것들은 모두 영속성컨텍스트에서 관리가 된다. 따라서 위의 코드에서 (1)
에 의해 더티체킹 즉 update쿼리가 나가게 된다.
Address address = new Address();
address.setCity("city1");
address.setStreet("street1");
address.setZipcode("zipcode1");
Order order = new Order();
order.setAddress(address);
em.persist(order);
em.flush();
em.clear();
List<Address> addressList =
em.createQuery("select o.address from Order o", Address.class)
.getResultList();
for(Address findAddress : addressList) {
System.out.println("findAddress.getCity() = " + findAddress.getCity());
System.out.println("findAddress.getStreet() = " + findAddress.getStreet());
System.out.println("findAddress.getZipcode() = " + findAddress.getZipcode());
}
스칼라 타입 프로젝션은 2가지 방법이 있다.
Member member = new Member();
member.setUsername("member1");
member.setAge(10);
em.persist(member);
em.flush();
em.clear();
List<Object[]> resultList =
em.createQuery("select m.username, m.age from Member m")
.getResultList();
Object[] result = resultList.get(0);
System.out.println("username = " + result[0]);
System.out.println("age = " + result[1]);
public class MemberDTO {
private String username;
private int age;
public MemberDTO(String username, int age) {
this.username = username;
this.age = age;
}
}
Member member = new Member();
member.setUsername("member1");
member.setAge(10);
em.persist(member);
em.flush();
em.clear();
List<MemberDTO> resultList =
em.createQuery("select new jpql.MemberDTO(m.username, m.age) from Member m")
.getResultList();
MemberDTO memberDTO = resultList.get(0);
System.out.println("memberDTO.getUsername() = " + memberDTO.getUsername()); // member1
System.out.println("memberDTO.getAge() = " + memberDTO.getAge()); // 10