public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try { for(int i = 0; i < 100; i++) { Member member = new Member(); member.setUsername("member" + i); member.setAge(i); em.persist(member); } em.flush(); em.clear(); // 페이징 처리 String jpql = "select m from Member m order by m.id "; List<Member> resultList = em.createQuery(jpql, Member.class) .setFirstResult(10) .setMaxResults(20) .getResultList(); System.out.println("result.size : " + resultList.size()); for(Member member1 : resultList) { System.out.println("member1 = " + member1.toString()); } tx.commit(); } catch (Exception e) { tx.rollback(); }finally { em.close(); emf.close(); } }
- 10번부터 20개 가져오기
// 조인 String sql = "select m from Member m inner join m.team t where t.name = :teamName"; List<Member> resultList = em.createQuery(sql, Member.class).getResultList();
// left outer join String sql = "select m from Member m left outer join m.team t"; List<Member> resultList = em.createQuery(sql, Member.class).getResultList();
from 절의 서브쿼리
는 현재 JPQL에서 불가능
하다.String sql = "select m from Member m where m.age > (select avg(m2.age) from Member m2)"; List<Member> resultList = em.createQuery(sql, Member.class).getResultList();
@Transactional(readonly = true)
가 계속 중복되기 때문에, 클래스 단위로 지정할 수도 있다. -> 변경 전
변경 후
-> readonly 조건이 아닌것만 @Transactional
어노테이션을 붙여준다.