H2 DB를 사용하기 전에는 매번 DBMS에 접속하여 스키마를 변경하며 진행했다.

프로젝트 초반에는 스키마 변경이 잦기 때문에 기존 방식은 효율적이지 못했다.

 

이미 많은 사람들이 H2 DB를 사용하여 개발을 진행하고 있을 것이기 때문에 글을 작성하는 것이 큰 의미는 없다 생각한다.

다만 메모리 DB 이기 때문에 외부에서 접속하기 위해서는 TCP 연결을 해야 한다.

이 부분이 안되는 경우가 있어서 나중에 다시 보려고 한다.

(Spring 보다는 Intellij 팁에 가깝다.)

 

필수 항목

  • Intellij Ultimate Edition (Intellij에 있는 Database tool을 사용하기 때문에)

 

1. Spring Boot Application 프로젝트 생성

2. 의존성 추가

dependencies {
    // Database
    implementation 'com.h2database:h2'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    // Etc
    implementation 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
    // Test
    testImplementation 'org.springframework.boot:spring-boot-starter-test'    
}

3. application.yml

spring:
  datasource:
    hikari:
      driver-class-name: org.h2.Driver
      jdbc-url: jdbc:h2:mem:public;
      username: sa
      password: 1234
  jpa:
    hibernate:
      ddl-auto: create-drop
      naming:
        implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
    show-sql: true
    database-platform: org.hibernate.dialect.H2Dialect
    properties:
      hibernate:
        format_sql: true
logging:
  level:
    org.hibernate: info
    org.springframework: info

4. Configuration

import java.sql.SQLException;
import javax.sql.DataSource;
import org.h2.tools.Server;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class H2DBConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource() throws SQLException {
        Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9093").start();
        return DataSourceBuilder.create().build();
    }
}

5. Entity 생성

import java.time.ZonedDateTime;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import lombok.Getter;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
@Getter
public abstract class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    private ZonedDateTime createdDate;

    private ZonedDateTime modifiedDate;

    @PrePersist
    public void createDate() {
        createdDate = ZonedDateTime.now();
        modifiedDate = createdDate;
    }

    @PreUpdate
    public void updateDate(){
        modifiedDate = ZonedDateTime.now();
    }

}
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Table(name = "users", indexes = @Index(name = "idx_user", columnList = "userId", unique = true))
@Entity
@Builder
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class User extends BaseEntity {

    @Column(nullable = false, length = 20)
    private String userId;

    @Column(nullable = false, length = 128)
    private String password;

    @Column(nullable = false, length = 20)
    private String name;
}

6. Application main (Test를 위한 코드이며 실무에서 따라 하지 마세요)

import com.example.h2db.domain.User;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class H2dbApplication implements CommandLineRunner {

    @PersistenceContext
    private EntityManager entityManager;

    public static void main(String[] args) {
        SpringApplication.run(H2dbApplication.class, args);
    }

    @Override
    @Transactional
    public void run(String... args) {
        User user = User.builder().userId("Kennen@email.com")
            .name("Kennen")
            .password("decryptedPassword")
            .build();

        entityManager.persist(user);
    }
}

7. 실행

./gradlew bootRun

8. Database Tool 확인

password는 application.yml 에 작성되어 있다.

 

이렇게 접근하면 된다.

이상.

+ Recent posts