본 내용은 유튜브 나무소리님의 강의 내용을 정리한 내용입니다.
1-4강 JPA 기초 실습(2)
persistence.xml
- persistence.xml은 JPA를 사용하여 데이터베이스에 접근하기 위한 환경 설정 파일입니다.
- resources/META-INF 패키지 안에 persistence.xml 파일을 생성하여야 합니다.
- Dialect은 Hibernate에서 데이터베이스와의 상호 작용에 사용되는 SQL 방언(또는 SQL Dialect)을 나타냅니다.
- Hibernate에서 Dialect를 설정하면 해당 DBMS에 맞춤형 SQL 쿼리문을 생성해줍니다.
// resources/META-INF/persistence.xml
<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="customer-exam">
<properties>
<!-- H2 DB -->
<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"/>
<!-- Option -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
Customer 객체를 DB에 저장
- JPA에서 데이터베이스와의 모든 작업은 트랜잭션 내에서 이루어져야 합니다.
- EntityManager의 persist() 메서드를 사용하여 Customer 객체를 저장합니다.
package com.example.jpa;
...
// 간소화 된 코드
public class CustomerJpaExam {
public static void main(String[] args) {
// EntityManager를 생성할 Factory 설정
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("customer-exam");
// EntityManager 생성
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//
entityManager.persist(Customer.sample()); // 엔티티 저장
//
transaction.commit();
entityManager.close();
entityManagerFactory.close();
}
}
- 하지만 main 메서드를 실행해보면 에러가 발생하는 것을 볼 수 있습니다.
Error Message
Exception in thread "main" java.lang.IllegalArgumentException: Unable to locate persister: com.example.jpa.entity.Customer
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:740)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:721)
at com.example.jpa.CustomerJpaExam.main(CustomerJpaExam.java:18)
- 위 에러는 Customer 객체를 Entity로 지정해 주지 않아서 발생하는 에러입니다.
- 위 에러를 해결하기 위해서는 Customer 클래스에 @Entity를 추가해줘야 합니다.
JPA annotation
- @Entity - JPA를 사용해서 DB 테이블과 매핑할 클래스 지정
- @Table - 엔티티와 매핑할 테이블 지정
- @Id - PK와 매핑할 변수를 지정
package com.example.jpa.entity;
...
@Entity // JPA를 사용해서 DB 테이블과 매핑할 클래스 지정
@Table(name = "customer_tb") // 엔티티와 매핑할 테이블 지정
public class Customer {
@Id // Primary Key 지정
private String id;
private String name;
private Long registerDate;
public Customer(String id, String name) {
this.id = id;
this.name = name;
this.registerDate = System.currentTimeMillis();
}
public static Customer sample() {
return new Customer("ID0001", "Kim");
}
}
- 위의 어노테이션을 추가한 후 실행을 하게 되면 아래와 같이 Hibernate에서 생성하여 실행한 SQL 쿼리문을 볼 수 있습니다.
- h2database에서 조회를 해보면 아래와 같이 데이터가 잘 저장된 것을 볼 수 있습니다.

