인프런 (자바 ORM 표준 JPA 프로그래밍 - 기본편, 김영한) 강의를 듣고 정리한 내용입니다
<persistence-unit name="hello"> //EntityManagerFactory 인자값이 됨
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.user" value="유저"/>
<property name="javax.persistence.jdbc.password" value="비밀번호"/>
<property name="javax.persistence.jdbc.url" value="url정보"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!-- 옵션 -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
<!--<property name="hibernate.hbm2ddl.auto" value="create" />-->
</properties>
</persistence-unit>
//웹서버 올라오는 시점에 1개만 생성됨
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
emf.close();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
//고객의 요청마다, 트랜잭션 단위마다 생성됨. 모든 데이터 변경은 트랜잭션 안에서 실행함
EntityManager em = emf.createEntityManager();
//code 들이 들어감
em.close();
emf.close();
//Member 객체만 만들었음
Member member = new Member();
member.setId(1L);
member.setName("helloA");
//Member 객체를 영속성 컨텍스트에 넣음
em.persist(member);
//영속성 분리함
em.detach(member);
//영속성 컨텍스트 완전히 초기화
em.clear();
//영속성 컨텍스트 종료
em.close()
//찾아서
Member findMember = em.find(Member.class, 1L);
//삭제함
em.remove(findMember);
-> 영속성 컨텍스트에 넣었다고 해서 바로 쿼리가 실행되지 않고 커밋 직전에 실행됨
Member member = new Member();
member.setId(2L);
member.setName("hello2");
System.out.println("=========== BEFORE =========");
em.persist(member);
System.out.println("=========== AFTER =========");
=========== BEFORE =========
=========== AFTER =========
Hibernate:
/* insert helloJpa.Member
*/ insert
into
Member
(name, id)
values
(?, ?)
-> flush를 사용하면 영속성 컨텍스트의 변경내용을 바로 DB에 반영함
System.out.println("=========== BEFORE =========");
em.persist(member);
em.flush();
System.out.println("=========== AFTER =========")
=========== BEFORE =========
Hibernate:
/* insert helloJpa.Member
*/ insert
into
Member
(name, id)
values
(?, ?)
=========== AFTER =========
System.out.println("=========== BEFORE =========");
em.persist(member); //영속화
Member findMember = em.find(Member.class, 3L); //영속성 컨텍스트에서 가져옴
System.out.println("이름 : "+findMember.getName());
System.out.println("=========== AFTER =========");
=========== BEFORE =========
이름 : hello3
=========== AFTER =========
Hibernate:
/* insert helloJpa.Member
*/ insert
into
Member
(name, id)
values
(?, ?)
Member findMember1 = em.find(Member.class, 4L);
Member findMember2 = em.find(Member.class, 4L);
System.out.println(findMember1 == findMember2); //true
Member findMember1 = em.find(Member.class, 4L);
findMember1.setName("hello~~!!!!");
update
Member
set
name=?
where
id=?