본문 바로가기

Spring/JPA

JPA- EntityManager.find()로 조회하기

package hellojpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

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 findMember = em.find(Member.class, 1L);  //DB에서 찾기
            findMember.setName("helloJpa");  //수정하기(업데이트 쿼리 날림)

            tx.commit();
        } catch(Exception e) {
            tx.rollback(); //오류 발생 시 롤백
        } finally {
            //종료
            em.close();
        }
        emf.close();
    }
}

 em.find(찾는 객체 클래스, id); 를 통해서 객체를 DB에서 찾아올 수 있다. 그리고 꺼내온 객체는 위에서처럼 set문 등을 이용해 수정을 하는 경우, 따로 persist와 같이 업데이트 쿼리를 안 날려줘도 자동으로 업데이트가 된다.

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

JPA- flush와 영속성 관리  (0) 2023.02.28
JPA- 영속성 컨텍스트  (0) 2023.02.28
JPA- 관련 개념 정리  (0) 2023.02.16
JPA- 지연 로딩과 즉시 로딩  (0) 2023.02.16
JPA- Transaction  (0) 2023.02.16