JPA ์ž‘๋™ ์›๋ฆฌ

JPA ๊ตฌ๋™ ๋ฐฉ์‹

JPA ๊ตฌ๋™ ๋ฐฉ์‹

  1. ๋จผ์ € Persistence ํด๋ž˜์Šค์—์„œ META-INF๋ผ๋Š” ํด๋” ์•„๋ž˜์—์„œ persistence.xml์˜ ์„ค์ • ์ •๋ณด๋ฅผ ์ฝ์–ด๋“ค์ธ๋‹ค.

  2. EntityManagerFactory์—์„œ EntityManager๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

  3. EntityManager๋ฅผ ํ†ตํ•ด ํŠธ๋žœ์žญ์…˜ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๊ณ  ํŠธ๋žœ์ ์…˜์„ ์‹œ์ž‘ํ•œ๋‹ค.

  4. Member Entity ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค

  5. Member์˜ ์ •๋ณด๋ฅผ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

  6. EntityManager์˜ persist ๋ฉ”์„œ๋“œ์— Member์„ ๋‹ด๋Š”๋‹ค.

  7. ํŠธ๋žœ์žญ์…˜ ๊ฐ์ฒด๋ฅผ ํ†ตํ•ด commit์„ ๋ณด๋‚ธ๋‹ค.

  8. ์ด๋•Œ try catch๋กœ ํŠธ๋žœ์žญ์…˜์˜ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, rollback ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค€๋‹ค.

  9. EntityManager๋ฅผ closeํ•œ๋‹ค.

  10. EntityManagerFactory๋ฅผ closeํ•œ๋‹ค.

์ฃผ์˜

  • EntityManagerFactory๋Š” ํ•˜๋‚˜๋งŒ ์ƒ์„ฑํ•ด์„œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ „์ฒด์—์„œ ๊ณต์œ  ๋œ๋‹ค.
  • EntityManager๋Š” ์“ฐ๋ ˆ๋“œ ๊ฐ„์— ๊ณต์œ ๋˜์ง€ ์•Š๋Š”๋‹ค.(์‚ฌ์šฉํ•˜๊ณ  ๋ฒ„๋ฆฐ๋‹ค)
  • JPA์˜ โ€˜๋ชจ๋“ โ€™ ๋ฐ์ดํ„ฐ ๋ณ€๊ฒฝ์€ ํŠธ๋žœ์ ์…˜ ์•ˆ์—์„œ ์‹คํ–‰๋œ๋‹ค.

์˜ˆ์ œ

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.setId(1L);
            member.setName("HelloA");

            em.persist(member);

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

์ถœ์ฒ˜: ์ž๋ฐ” ORM ํ‘œ์ค€ JPA ํ”„๋กœ๊ทธ๋ž˜๋ฐ - ๊ธฐ๋ณธํŽธ