본문 바로가기
Java/JPA

[JPA_Basic] JPA persist, find, remove, update

by HJ0216 2023. 6. 15.

이 글은 김영한의 [자바 ORM 표준 JPA 프로그래밍 - 기본편] 수강하며 정리한 글입니다.

 

 

🟦 기본 환경: IDE: IntelliJ, Language: Java

 

 

Persistence.xml

: JPA가 접근하고자하는 DB에 대해 필요한 설정 정보들을 기술해둔 파일

→ JPA는 이 파일의 설정 정보를 바탕으로 접근할 DB의 정보를 가져 올 수 있음

 

EntityManagerFactory

: EntityManager(Entity를 관리하고 DB 관련 작업을 수행 함)를 생성

: DB 당 1개 생성

 

EntityManager

: 특정 작업을 위해 데이터베이스에 액세스 하는 역할

: DB에 저장되는 transaction 단위마다 생성

 

EntityTransaction

: 데이터베이스 트랜잭션을 관리하기 위한 인터페이스로, 트랜잭션의 시작, 커밋, 롤백 등의 작업을 수행하는 메서드를 제공

: JPA의 모든 데이터 변경은 transaction 안에서 실행

 

Transaction Structure

: commit과 rollback이 try-catch 구조를 이뤄야하며, 반드시 Entity Manager가 종료될 수 있도록 finally 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        // EntityManagerFactory: Application Loading 시점에 1개만 생성(DB당 1개)
 
        EntityManager em = emf.createEntityManager();
        // EntityManager: DB에 저장되는 transaction 단위마다 생성
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin(); // transaction 시작 선언
 
        try {
                // 실행하고자하는 코드
            }
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
        emf.close();
 
    }
}
 
 
 

 

JPA - 회원 가입

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        // EntityManagerFactory: Application Loading 시점에 1개만 생성(DB당 1개)
 
        EntityManager em = emf.createEntityManager();
        // EntityManager: DB에 저장되는 transaction 단위마다 생성
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin(); // transaction 시작 선언
 
        try {
                Member member = new Member();
                member.setId(2L);
                member.setName("HelloB");
                em.persist(member);
            }
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
        emf.close();
 
    }
}
 
 
 

 

JPA - 회원 조회

: 조회의 경우, commit이 필요없으므로 try-catch 구문 불필요

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        // EntityManagerFactory: Application Loading 시점에 1개만 생성(DB당 1개)
 
        EntityManager em = emf.createEntityManager();
        // EntityManager: DB에 저장되는 transaction 단위마다 생성
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin(); // transaction 시작 선언
 
        try {
                Member findMember = em.find(Member.class, 1L);
                // 1번째 parameter: Entity Class, 2번째 parameter: PK
                System.out.println("id: " + findMember.getId());
                System.out.println("name: " + findMember.getName());
            }
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
        emf.close();
 
    }
}
 
 
 

 

JPA - 회원 삭제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        // EntityManagerFactory: Application Loading 시점에 1개만 생성(DB당 1개)
 
        EntityManager em = emf.createEntityManager();
        // EntityManager: DB에 저장되는 transaction 단위마다 생성
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin(); // transaction 시작 선언
 
        try {
                Member findMember = em.find(Member.class, 1L);
                em.remove(findMember);
            }
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
        emf.close();
 
    }
}
 
 
 

 

JPA - 회원 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        // EntityManagerFactory: Application Loading 시점에 1개만 생성(DB당 1개)
 
        EntityManager em = emf.createEntityManager();
        // EntityManager: DB에 저장되는 transaction 단위마다 생성
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin(); // transaction 시작 선언
 
        try {
                Member findMember = em.find(Member.class, 1L);
                findMember.setName("HelloJPA");
 
                tx.commit(); // update를 작성하지 않아도 findMember 내용의 변경이 있을 경우, JPA 자동 update query 생성
            }
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
        emf.close();
 
    }
}
 
 
 

 

 + JPA - 전체 회원 조회

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package jpa_basic;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
 
public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        // EntityManagerFactory: Application Loading 시점에 1개만 생성(DB당 1개)
 
        EntityManager em = emf.createEntityManager();
        // EntityManager: DB에 저장되는 transaction 단위마다 생성
 
        // JPA의 모든 데이터 변경은 transaction 안에서 실행
        EntityTransaction tx = em.getTransaction();
        tx.begin(); // transaction 시작 선언
 
        try {
                List<Member> result = em.createQuery("select m from Member as m", Member.class)
                        .setFirstResult(0)
                        .setMaxResults(5)
                        .getResultList();
 
                for(Member member : result) {
                    System.out.println("member.name: " + member.getName());
            }
 
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            em.close();
        }
 
        emf.close();
 
    }
}
 
 
 

createQuery

: EntityManager(em) 객체를 사용하여 쿼리를 생성하는 메서드

: JPA의 객체지향 쿼리 언어인 JPQL을 사용, Entity Class 사용

 

setFirstResult

: 조회 결과 중에서 첫 번째로 가져올 레코드의 인덱스를 설정

 

setMaxResults

: 최대로 가져올 결과 레코드 수를 설정

 

getResultList

: 쿼리를 실행하고 결과를 리스트 형태로 반환

 

 

 

참고 자료

 

JPA 작동 메커니즘

JAVA의 ORM 표준 : JPA 이전 포스팅에서 SQL 중심적인 개발의 문제점을 살펴보고 해결방법으로 JAVA의 ORM 표준인 JPA를 가볍게 언급해보았다. 그렇다면, JAVA에서는 JPA을 어떻게 지원하고 개발자들이 지

velog.io

 

'Java > JPA' 카테고리의 다른 글

[JPA] JOIN Null값 처리  (0) 2023.06.20
[SpringBoot_JPA_Basic] JPA 1차 cache  (0) 2023.06.16
[SpringBoot_JPA_1] @PathVariable  (0) 2023.06.03
[SpringBoot_JPA_1] TypedQuery  (0) 2023.06.02
[SpringBoot_JPA_1] @NoArgsConstructor  (1) 2023.05.30