@Entity
@Table(name = "tickets")
public class Ticket {
@Id // Id PK
private long id;
private long price;
private LocalDate reservedDate;
// getter and setter
}
JPA 이용에 가장 중요한 핵심 요소
Entity는 반드시 식별자 값 가짐.
EntityManager em = emf.createEntityManager(); // 1)엔티티 매니저 생성
EntityTransaction transaction = em.getTransaction(); // 2)트랜잭션 획득
transaction.begin(); // 3)트랙잰셕 begin
Customer customer = new Customer(); // 4-1)비영속
customer.setId(1L);
customer.setFirstName("honggu");
customer.setLastName("kang");
// entity를 key-value로 1차 캐시에 저장
// 쿼리를 쓰기 지연 저장소에 저장
em.persist(customer); // 4-2)영속화
// 트랜잭션이 커밋이 되는 순간 쿼리가 수행된다. flush DB와 동기화가 된다.
// 커밋 순간 flush
// flush되면, 1차 캐시에 있던 내용, 쓰기 지연 저장소에 있던 쿼리가 실행
transaction.commit(); // 5)트랜잭션 commit
조회
영속성 컨텍스트 내 1차 캐시에 Entity에 대한 key-value가 있는 경우
DB까지 가지 않음
1차 캐시에서 결과 찾아서 반환
SQL 실행 X
em.persist(customer);
transaction.commit();
// 1차 캐시에서 조회
Customer entity = em.find(Customer.class, 1L);
1차 캐시에 entity에 대한 key가 없는 경우
DB에서 결과 반환
SQL 실행 O
em.persist(customer);
transaction.commit();
em.clear();
// DB에서 조회 -> SQL 실행
Customer entity = em.find(Customer.class, 2L);
// 1차 캐시에서 조회 -> SQL 쿼리 실행 X
em.find(Customer.class, 2L);
수정
em.persist(customer);
// entity 영속화 후, 커밋(flush()) 통해 DB 저장
transaction.commit();
transaction.begin();
Customer entity = em.find(Customer.class, 1L);
entity.setName("다른이름");
// entity를 update하지 않아도,
// 더티체킹으로 entity 와 스냅샷 비교 후
// commit 시점에 쿼리 날려줌
transaction.commit();
삭제
em.persist(customer);
transaction.commit();
transaction.begin();
Customer entity = em.find(Customer.class, 1L);
em.remove(entity);
transaction.commit(); // flush -> DELETE ..