본문 바로가기
개발 이론/Spring

[Spring] flyway - BaseJavaMigration?

by dal_been 2023. 11. 13.
728x90

flyway는 sql파일뿐만 아니라 java 파일또한 migration  가능하다.

파일명은 이전에 sql파일이름 짓을때 처럼 해주면 되고 경로는 src/java/db/migration경로를 생성해줘 안에 java파일을 생성하면된다

import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;

import java.sql.ResultSet;
import java.sql.Statement;

public class V3__bulk_update_books extends BaseJavaMigration {
    @Override
    public void migrate(Context context) throws Exception {
        try (Statement select = context.getConnection().createStatement()) {
            try (ResultSet rows = select.executeQuery("SELECT id FROM books ORDER BY id")) {
                while (rows.next()) {
                    int id = rows.getInt(1);
                    String nameToChange = "test";
                    try (Statement update = context.getConnection().createStatement()) {
                        update.execute("UPDATE books SET name='" + nameToChange + "'WHERE id=" + id);
                    }
                }
            }
        }
    }
}

 

BaseJavaMigration을 상속받아 migrate함수를 override하면 된다

 

books 엔티티를 이용해서 모든 데이터를 가져온후 이름을 "test"로 바꾸엇다

 

https://documentation.red-gate.com/fd/tutorial-java-based-migrations-184127624.html

 

Tutorial - Java-based Migrations - Flyway - Product Documentation

Tutorial - Java-based Migrations Page last updated 31 October 2023 Published 16 November 2022 Tutorial: Java-based Migrations This tutorial assumes you have successfully completed the Quickstart: Maven tutorial. If you have not done so, please do so first.

documentation.red-gate.com