목차

JPA persistence.xml

기본 persistence.xml 뼈대

2.0

<?xml version="1.0" encoding="utf-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="unitname" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <mapping-file>ormap.xml</mapping-file> <!-- 필요할 경우 -->
        <class>org.acme.Employee</class>
        <class>org.acme.Person</class>
        <class>org.acme.Address</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db1"/>
            <property name="javax.persistence.jdbc.user" value="sa"/>
            <property name="javax.persistence.jdbc.password" value=""/>
        </properties>
    </persistence-unit>
</persistence>

2.1

<?xml version="1.0" encoding="UTF-8" ?>
<persistence 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_1.xsd"
             version="2.1">
    <persistence-unit name="unitname" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
...
    </persistence-unit>
</persistence>

기본 테스트

JPA에 대한 기본 테스트는 다음과 같이 할 수 있다. /src/test/resources/META-INF/persistence.xml이 있다고 간주한다.

@Slf4j
public class GenericJPATest {
 
    private static EntityManagerFactory emf;
 
    private EntityManager em;
    private EntityTransaction transaction;
 
    @BeforeClass
    public static void setUpClass() throws Exception {
        // 필요한 경우 아래에서 Map으로 프라퍼티들을 넘길 수 있다.
        emf = Persistence.createEntityManagerFactory("[test-persistence-unit]");
 
    }
 
    @AfterClass
    public static void tearDownClass() throws Exception {
        if (emf != null) {
            emf.close();
        }
    }
 
    @Before
    public void setUp() throws Exception {
        em = emf.createEntityManager();
 
        transaction = em.getTransaction();
    }
 
    @After
    public void tearDown() throws Exception {
 
        if (em != null) {
            em.close();
        }
    }
 
    @Test
    public void test() throws Exception {
        transaction과 em을 사용해 테스트
    }
}