[JPA 기초] 01. JPA 시작하기

Date:     Updated:

카테고리:

태그:

환경 설정 & 프로젝트 생성

1. H2 Database

[H2] 버전 확인 명령어

2. Maven 프로젝트 생성

[IntelliJ] 인텔리제이 maven 프로젝트 생성하기

Your relational data. Objectively. - Hibernate ORM

Spring Boot Reference Documentation

jpa-20240102

JPA, Hibernate, H2 database → Spring Boot를 지원하는 버전으로 설치하는게 가장 좋다

3. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>jpa-basic</groupId>
    <artifactId>ex1-hello-jpa</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- JPA 하이버네이트 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.6.15.Final</version>
        </dependency>
        <!-- H2 데이터베이스 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>2.2.224</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

Maven 프로젝트에 라이브러리를 추가하기 위해 사용되는 설정 xml 파일

4. 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>
  • JPA 설정에 사용되는 xml 파일
  • src/main/resources/META-INF/persistence.xml 에 위치한다
  • show_sql, format_sql, use_sql_comments 등은 디버깅을 할 때 JPA로 짠 코드를 SQL로 변환하여 보여줄 것인지에 대한 옵션이다.

애플리케이션 개발

JPA를 활용한 Spring Boot의 기본적인 형태는 아래와 같다.

1. Member

@Entity
public class Member {

    @Id
    private Long id;

    @Column(name = "name", nullable = false)
    private String username;

    public Member() {

    }

    /* Getter & Setter */

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
  • @Entity : JPA가 관리할 객체
  • @Id : DB PK와 매핑

2. Main

public class JpaMain {

    public static void main(String[] args) {

        /* Entity Manager Factory 생성 */
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");

        /* Entity Manager 생성 */
        EntityManager em = emf.createEntityManager();

        /* Transaction 실행 */
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        try {
            /* Member 생성 */
            Member member1 = new Member();
            member1.setUsername("A");

            /* 객체 저장 -> 영속성 컨텍스트, not DB */
            em.persist(member1);

            /* Member 조회 */
            System.out.println("member1.getId() = " + member1.getId());

            /* Member 수정 */
            member1.setUsername("B")

            /* 객체 저장 -> DB commit */
            tx.commit();
        } catch (Exception e) {
            tx.rollback();

        } finally {
            /* Entity Manager 종료 */
            em.close();
        }
        /* Entity Manager Factory 종료 */
        emf.close();
    }
}

JPA 카테고리 내 다른 글 보러가기

댓글 남기기