JPA - 2강 (수정/삭제)

지환·2024년 5월 1일

JPA

목록 보기
3/5

예외처리

지난 시간엔 예외처리가 진행되지 않았기 때문에 예외처리를 진행하겠다.

public class CustomerJpaExam {

    public static void main(String[] args) {
        EntityManagerFactory  emf = Persistence.createEntityManagerFactory("customer-exam");
        /*entityManager를 얻어오기 위한 작업*/

        EntityManager em = emf.createEntityManager();
        // 하나의 엔티티 매니저를 갖게 됐음
        // 항상 트랜잭션 단위로 작업된다. (커밋 <-> 롤백) * 단위에 대해서 숙지해야한다. *

        EntityTransaction tx = em.getTransaction();

        tx.begin();
        /*
            em.persist(); 내가 넣을 객체를 persist() 파라미터 안에다 넣으면 된다.
        * */

        try{
            em.persist(Customer.sample());
            tx.commit();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }finally {
            em.close();
            emf.close();
        }


    }
}

만약에 값을 가져온다면?

        try{
            Customer customer = em.find(Customer.class,"ID0001"); // ID0001 은 PK값임
            System.out.println(customer.toString());

            tx.commit();
        }
  • 이런식으로 가져올 수 있음

  • Customer.class를 인스턴스화를 진행 -> 관련된 필드를 세팅해서 보내야함

  • 즉 Customer 객체를 entity매니저가 생성해서 보낼 수 있어야함 -> 디폴트 생성자가 존재해야함

    • 디폴트 생성자로 entityManager가 생성함 -> 그렇기 때문에 생성자가 필요함
  • 필요한 이유가 중요함

Hibernate: 
    select
        c1_0.id,
        c1_0.name,
        c1_0.registerDate 
    from
        customer_tb c1_0 
    where
        c1_0.id=?
io.namoosori.jpa.entity.Customer@6f911326

이렇게 잘 쿼리문을 가져오는 것을 알 수 있다.

Update

ublic class CustomerJpaExam {

    public static void main(String[] args) {
        EntityManagerFactory  emf = Persistence.createEntityManagerFactory("customer-exam");
        /*entityManager를 얻어오기 위한 작업*/

        EntityManager em = emf.createEntityManager();
        // 하나의 엔티티 매니저를 갖게 됐음
        // 항상 트랜잭션 단위로 작업된다. (커밋 <-> 롤백) * 단위에 대해서 숙지해야한다. *

        EntityTransaction tx = em.getTransaction();

        tx.begin();
        /*
            em.persist(); 내가 넣을 객체를 persist() 파라미터 안에다 넣으면 된다.
        * */

        try{


            Customer customer = em.find(Customer.class,"ID0001"); // ID0001 은 PK값임
            customer.setName("Park"); // 가져온 객첵 값을 바뀜 // Transaction begin - commit 사이에서 일어났기 때문에 ---> 필드들을 수정한다.
            /*
            우리가 따로 Update를 하지 않았는데, Update가 진행됐음
            * */

            tx.commit();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }finally {
            em.close();
            emf.close();
        }


    }
}

Hibernate: 
    select
        c1_0.id,
        c1_0.name,
        c1_0.registerDate 
    from
        customer_tb c1_0 
    where
        c1_0.id=?
Hibernate: 
    /* update
        io.namoosori.jpa.entity.Customer */ update customer_tb 
    set
        name=?,
        registerDate=? 
    where
        id=?
  • 이렇게 update가 진행된다.

  • 이 객체는 entity 매니저를 통해 관리되고 있다. 관리되어지고 있다. 이 과정에서 이 값이 변경되면 커밋이 되면 자동으로 Update를 진행해준다. (별도의 Update를 진행하지 않는다.)

삭제 (remove)

        try{


            Customer customer = em.find(Customer.class,"ID0001"); // ID0001 은 PK값임
            em.remove(customer);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }finally {
            em.close();
            emf.close();
        }

profile
아는만큼보인다.

0개의 댓글