본문 바로가기

개발/스프링 프레임워크

[Spring Boot] H2 + JPA 세팅

 

 

1. Gradle Dependencies 추가

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.214'

 

* dependency 추가시 로컬 PC에 설치된 h2 버전과 동일하게 맞추는것이 좋다. 

 

 

2. application.properteis 추가 

#setting h2
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

#setting h2 db
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

#show sql
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true

#ddl auto
spring.jpa.hibernate.ddl-auto=create

 

3. Sample Entity 추가

package com.beomun.sharebook.domain.sample.entity;

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

@Entity
public class Sample {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String content;

    protected Sample() {}

    public Sample(String content) {
        this.content = content;
    }

    public Long getId() {
        return id;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

 

실행결과(sql 자동 생성)

Hibernate: 
    
    create table sample (
       id bigint not null,
        content varchar(255),
        primary key (id)
    )