Java/Spring Boot

[Spring Boot] 데이터베이스 마이그레이션 - Flyway

hh_lin 2022. 4. 17. 22:08

1. 의존성 추가

<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
</dependency>

 

 

 

 

 

 

 

 

2. 마이그레이션 디렉토리

  • db/migration 또는 db/migration/{vendor} (특정 벤더마다 만들 수도 있음)
  • spring.flyway.locations로 변경 가능

ex) resources/db/migration

 

 

 

 

 

 

 

 

 

 

 

3. 마이그레이션 파일 이름

  • V숫자__이름.sql 
  • V는 꼭 대문자로
  • 숫자는 순차적으로 (타임스탬프 권장)
  • 숫자와 이름 사이에 언더바 두 개
  • 이름은 가능한 서술적으로

ex) V1__init.sql

 

 

 

# 마이그레이션 디렉토리 안에 마이그레이션 파일이 없는 경우

 

 

 

# 파일 이름이 소문자로 시작하는 경우

 

 

 

# 정상적으로 실행 시 

-- V1__init.sql
drop table if exists account;
drop sequence if exists hibernate_sequence;
create sequence hibernate_sequence start 1 increment 1;
create table account (id bigint not null, password varchar(255), username varchar(255), primary key (id));

 

-> account, flyway_schema_history 테이블 생성

 

 

 

 

 

# 컬럼 추가 후 어플리케이션 재실행 시

매핑이 되지 않는 컬럼이 들어있기 때문에 hibernate가 validation하다가 오류 발생

-> 변경 필요시 기적용된 스크립트(V1__init.sql)를 수정하는 것이 아니라 반드시 새 스크립트를 추가해서 진행해야 함

--V2__add_column.sql
ALTER TABLE ACCOUNT ADD COLUMN EMAIL VARCHAR(255);
ALTER TABLE ACCOUNT ADD COLUMN ACTIVE BOOLEAN;

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com

https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#howto-execute-flyway-database-migrations-on-startup

 

Spring Boot Reference Guide

This section dives into the details of Spring Boot. Here you can learn about the key features that you may want to use and customize. If you have not already done so, you might want to read the "Part II, “Getting Started”" and "Part III, “Using Spr

docs.spring.io