Spring/Spring Data JPA

[자바 ORM 표준 JPA 프로그래밍] 2. JPA 시작

noahkim_ 2023. 11. 28. 00:21

김영한 님의 "자바 ORM 표준 JPA 프로그래밍" 책을 정리한 포스팅 입니다.

 

2. JPA 시작

애플리케이션 개발

public class JpaMain {

    public static void main(String[] args) {

        // 엔티티 매니저 팩토리 생성
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpabook");
        EntityManager em = emf.createEntityManager(); // 엔티티 매니저 생성
        EntityTransaction tx = em.getTransaction();   // 트랜잭션 기능 획득

        try {
            tx.begin();  // 트랜잭션 시작
            logic(em);   // 비즈니스 로직
            tx.commit(); // 트랜잭션 커밋
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback(); //트랜잭션 롤백
        } finally {
            em.close();  // 엔티티 매니저 종료
        }

        emf.close();     // 엔티티 매니저 팩토리 종료
    }
}

 

EntityManagerFactory
  • usage
    • create & manage connection pool 
    • create EntityManager instance
  • singleton: high cost to create

 

EntityManager
  • database communication: use a datasource to get a connection when needed to communicate
  • execute queries to the database through entity
  • thread-safe: no share or reuse among threads

 

EntityTransaction
  • obtain from EntityManager
  • perform transaction operations
    • must be performed within transation. (otherwise, exception will be thrown)

 

JPQL

  • OOP Query Language (SQL-Abstraction)

 

Entity-based query
  • Indirectly handles database tables through entity
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private double price;

    // Getters and setters
}
  • Queries are performed on entities (no SQL)
String jpql = "SELECT e FROM Employee e WHERE e.department = :dept";
TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
query.setParameter("dept", "HR");
List<Employee> results = query.getResultList();