Spring

[Spring boot] SQL script 를 활용한 DB 초기화

woopii 2022. 2. 3. 00:37

● schema.sql, data.sql 파일로 DB 초기화

1. 샘플용 schema.sql, data.sql 생성

 

## 파일 위치

## schema.sql

DROP TABLE tb_sample IF EXISTS;

CREATE TABLE tb_sample ( 
	id bigint generated by default as identity, 
	name varchar(255) not null,
	primary key (id) 
);

## data.sql

INSERT INTO tb_sample (id, name) values (1, 'sample1');

 

2. application.yml 수정

## spring.datasource.schema : schema.sql 파일 지정

## spring.datasource.data : data.sql 파일 지정

## spring.datasource.initialization-mode : 기동시 schema.sql, data.sql 스크립트를 읽을 지 여부 (always, never)

database: h2db

spring:
    h2:
        console:
            enabled: true
            path: /h2-console

    datasource:
        driverClassName: org.h2.Driver
        #url: jdbc:h2:file:./target/h2db/db/application;DB_CLOSE_DELAY=-1
        url: jdbc:h2:mem:testdb
        username: sa
        password:
        # DB초기화(schema.sql, data.sql) , [always : 기동 시 매번 동작, never : 기동 시 동작하지 않음]
        schema: classpath*:initdata/${database}/schema.sql
        data: classpath*:initdata/${database}/data.sql
        #schema: classpath*:initdata/h2db/schema.sql
        #data: classpath*:initdata/h2db/data.sql
        initialization-mode: always

 

3. 동작 확인

 

'Spring' 카테고리의 다른 글

[Spring Boot] Mybatis Sample  (0) 2022.02.05
[spring boot] JPA sample  (0) 2022.02.04
[Spring Boot] H2DB JDBC연동  (0) 2022.02.02
[Spring Boot] profiles 변경  (0) 2022.02.02
[Spring Boot] 프로젝트 생성 및 시작하기 (Visual Studio Code)  (0) 2021.09.18