[JPA] JQPL 사용해서 페이징 수행

반응형
728x90
반응형

예제코드

Member.java
package jpql;

import javax.persistence.*;

@Entity
@Table(name="MEMBER")
@Getter
@Setter
public class Member {

    @Id
    @GeneratedValue
    private Long id;

    private String username;
    private int age;
	
    ...
}

 

Main.java
package main.paging;

import jpql.Member;

import javax.persistence.*;
import java.util.List;

public class JpaMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager(); //엔티티 매니저 생성
        EntityTransaction tx = em.getTransaction(); //트랜잭션 기능 획득

        tx.begin();

        try {
            Member member = new Member();
            member.setUsername("kimseohae");
            member.setAge(10);

            em.persist(member);

            // as m 필수
            TypedQuery<Member> query = em.createQuery("select m from Member as m order by m.age desc", Member.class)
                    .setFirstResult(0) // 0 : limit ? // 0 이상 : limit ? offset ?
                    .setMaxResults(10);

            List<Member> resultList = query.getResultList();
            System.out.println("result.size = " + resultList.size());
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback(); //트랜잭션 롤백
        } finally {
            em.close(); //엔티티 매니저 종료
        }
    }
}

 

STEP1. createQuery()

// as m 필수
TypedQuery<Member> query = em.createQuery("select m from Member as m order by m.age desc", Member.class)
        .setFirstResult(0)
        .setMaxResults(10);

 

- setFirstResult(0) 일 경우
limit ?

 

- setFirstResult(1) 일 경우 (0이 아닌 경우)
limit ? offset ?

 

 

STEP2. getResultList()를 사용하여 여러 row를 List 객체에 담고 size 출력

List<Member> resultList = query.getResultList();
System.out.println("result.size = " + resultList.size());

 

 

반응형

Designed by JB FACTORY