Persistence라는 클래스가 persistence.xml 이라는 설정 파일을 읽고 EntitiyManagerFactory를 생성합니다. 그리고 EntityManagerFactory는 필요할 때 EntityManager을 만든다.
이 과정을 코드로 봐보자.
persistence.xml 파일이 아래와 같다고 하자.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="hello">
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
<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>
</persistence>
public class JpaMain {
private EntityManager em;
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
em.close();
emf.close();
}
}
Persistence가 EntityManagerFactory를 만드는데 이것은 persistence.xml 파일 기반이다. 여기서
Persistence.createEntityManagerFactory("hello"); 의 hello는 persistence.xml에서 persistence-unit name="hello" 값이다.
즉 이 properties를 기반으로 EntityManagerFactory를 만드는 것이고, EntityManagerFactory는 필요한 경우 EntityManager을 만든다.
그리고 EntityManager는 데이터베이스 커넥션을 통해서 DB를 사용하게 된다.
[ JPA ] 양방향 연관관계(1) - mappedBy (0) | 2022.01.07 |
---|---|
[ JPA ] 단방향 연관관계 (0) | 2021.12.30 |
[ JPA ] @Entity (0) | 2021.12.19 |
[ JPA ] JPA로 DB 데이터 삽입 (0) | 2021.12.16 |
[ JPA ] 영속성 컨텍스트란? (0) | 2021.08.01 |