JPA

[JPA] Gradle + H2 JPA 실습환경 셋팅

Yerim Kim 2021. 4. 26. 10:54

1. h2 database 를 설치하고 서버모드로 실행했음. 그리고 테이블 생성

create user (
   id bigint primary key auto_increment,
   name varchar(200) not null,
   age int
);

  

 

 

2. 프로젝트 생성

IntelliJ로 Gradle 프로젝트를 대충 생성한다음..

 

1. build.gradle에 의존성 추가

implementation 'org.hibernate:hibernate-entitymanager:4.3.10.Final'
runtimeOnly 'com.h2database:h2:1.4.187'

 

2. src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
  <persistence-unit name="practice">

    <class>practice.domain.User</class>

    <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.id.new_generator_mappings" value="true"/>

    </properties>
  </persistence-unit>
</persistence>
  • JPA에서 필요로하는 설정 정보를 이 파일로 관리한다.
  • 설정파일 경로가 클래스패스 경로/META-INF/persistence.xml 이면 별도의 설정 없이 JPA가 인식한다.

 

 

3. 코드작성

package practice.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = true)
    private Integer age;

    protected User() {} // 엔티티에 public or protected 기본생성자 필수

    public User(Long id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}
  • 엔티티 클래스 : 테이블과 매핑할 클래스
    • 기본생성자 필수
    • final 필드 불가
package practice;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import practice.domain.User;

public class Main {

    public static void main(String[] args) {
        EntityManagerFactory entityManagerFactory =
            Persistence.createEntityManagerFactory("practice");

        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();

        try {
            transaction.begin();

            entityManager.persist(new User(null, "해위", 25));

            transaction.commit();

        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            entityManager.close();
        }
        entityManagerFactory.close();
    }
}

   

 

   

실행결과

insert 문이 잘 실행된것을 확인할 수 있다.