rainsister
  • 신비한 비 Blog
  • Design Pattern
    • Adapter Pattern
    • Proxy Pattern
    • Mediator Pattern
    • Visitor Pattern
    • State Pattern
    • Memento Pattern
    • Factory Pattern
    • Template Pattern
    • Strategy Pattern
    • Bridge Pattern
  • springboot 2.x
    • 메시징 - 큐
      • RabbitMQ 기본설정
      • RabbitMQ 지연 큐(delayed queue)
    • Log
      • 기본 Log 설정 및 Logback 설정
      • Log4j2 사용해보기
      • tinylog 모듈 사용해보기
    • 기타 Database 에 대한 기본가이드
      • PostgreSQL
      • InfluxDB
      • MongoDB
    • 수행속도 UP! 각종 cache 어노테이션 사용법
      • Redis를 사용하여 Cache 관리하기
      • EhCache 사용해보기
      • Thread내캐쉬사용 및 Cache 어노테이션 사용법
    • Database Connection
      • Springboot 2.5 이후 data init script 초기화에 대한 변경
      • JTA 로 JPA 다중 DataSource 트랜잭션 처리 하기
      • Flyway 로 DataBase 형상 관리해보자
      • 트랜잭션 기초읽기
      • MyBatis 의 다중 DataSource
      • Spring Data JPA 다중 DataSource
      • JdbcTemplate 다중 DataSource
      • XML 로 Mybatis 설정하기
      • Mybatis 로 Mysql 연결하기
      • ORM(Spring data jpa)
      • Druid datasource 연결
      • Hikari 설정
      • JdbcTemplate 로 db 접근
    • rest api
      • XML에 대한 요청 및 응답 처리
      • SpringFox 3 및 Swagger 설정
      • 프로젝트 구동 시 RequestMappingHandler 로그 설정
      • Swagger 의 api들을 분류하는 법
      • 간단한 Restful API 만들고 테스트 코드 작성
      • Swagger2 구성하여 API 문서 자동화하기
      • JSR-303 그리고 validation
    • 설정
      • 시작
      • 멀티환경구성에 대한 새로운 방법
      • 멀티환경구성에 대한 새로운 include
      • 프로젝트 설정파일
      • 민감한 정보에 대한 암호화
  • java버전별차이
    • JAVA18
    • JAVA9
    • JAVA10
    • JAVA11
    • JAVA14
    • JAVA15
    • JAVA17
    • JAVA16
  • spring노하우
    • BeanUtils 권장하지 않는이유
    • 개인정보 암호화
    • Springboot 3가지 CROS 설정
    • Springboot 내장된 유용한 Utils
    • Spring Security WebSecurityConfigurerAdapter 가 deprecated 된 이슈해결하기
    • 아직도 HttpUtil ? SpringBoot 3.0의 HTTP Client Util 을 사용해보라
    • JDBC 소스를 뽀개기
    • spring-boot-configuration-processor 는 뭐하는놈임?
    • Apache BeanUtils vs Spring BeanUtils 성능비교
  • Effetive Java 3th
    • Finalizer & Cleaner
Powered by GitBook
On this page
  • pom.xml dependency 추가
  • User 객체 생성
  • Interface 작성
  • 테스트 코드 작성
  1. springboot 2.x
  2. Database Connection

Flyway 로 DataBase 형상 관리해보자

PreviousJTA 로 JPA 다중 DataSource 트랜잭션 처리 하기Next트랜잭션 기초읽기

Last updated 8 months ago

git 으로 source code 를 관리할수 있는건 누구나 다 아는 사실. 하지만 db는 할수 없다. 이 처럼 db의 형상관리를 할수 는 녀석이 바로 Flyway 다 .

공식사이트에 기재되어 있는 flyway 작동방식을 설명해주는 많이 보았을 이미지 이다.

flyway를 잘 사용하면 이렇게 Axel 과 Christian 라는 개발자 각자 필요한 DDL 을 만들고 배포할수 잇다. 공식사이트 소개를 예로 들자면 gradle, maven, CLI, java api 를 통하여 flyway 를 실행할수 있다고 하는데 이글에서 springboot 으로 실행하는 방법을 알아보자.

pom.xml dependency 추가

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

src/main/resources 폴더에 db 폴더 ,그리고 그안에 migration 폴더를 만든다.

migration 폴더에 V1__Base_version.sql 파일을 생성

DROP TABLE IF EXISTS user ;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'pk',
  `name` varchar(20) NOT NULL COMMENT '이름',
  `age` int(5) DEFAULT NULL COMMENT '나이',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

주의 : .sql 경로를 혹시 자기가 원하는 폴더에 위치하고 싶으면 spring.flyway.locations 설정을 하면 된다.

User 객체 생성

@Data
@NoArgsConstructor
public class User {

    private Long id;
    private String name;
    private Integer age;

}

Interface 작성

public interface UserService {

    int create(String name, Integer age);
    
    List<User> getByName(String name);

    int deleteByName(String name);

    int getAllUsers();

    int deleteAllUsers();

}

@Service
public class UserServiceImpl implements UserService {

    private JdbcTemplate jdbcTemplate;

    UserServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int create(String name, Integer age) {
        return jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
    }

    @Override
    public List<User> getByName(String name) {
        List<User> users = jdbcTemplate.query("select * from USER where NAME = ?", (resultSet, i) -> {
            User user = new User();
            user.setId(resultSet.getLong("ID"));
            user.setName(resultSet.getString("NAME"));
            user.setAge(resultSet.getInt("AGE"));
            return user;
        }, name);
        return users;
    }

    @Override
    public int deleteByName(String name) {
        return jdbcTemplate.update("delete from USER where NAME = ?", name);
    }

    @Override
    public int getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }

    @Override
    public int deleteAllUsers() {
        return jdbcTemplate.update("delete from USER");
    }

}

테스트 코드 작성

@Slf4j
@SpringBootTest
public class FlywayDemoApplicationTests {

    @Autowired
    private UserService userSerivce;

    @Test
    public void test() throws Exception {
        userSerivce.deleteAllUsers();

        userSerivce.create("Tom", 10);
        userSerivce.create("Mike", 11);
        userSerivce.create("Didispace", 30);
        userSerivce.create("Oscar", 21);
        userSerivce.create("Linda", 17);

        // Oscar 라는 이름을 가진 사용자 조회 , 나이 가 정확한지 확인.
        List<User> userList = userSerivce.getByName("Oscar");
        Assertions.assertEquals(21, userList.get(0).getAge().intValue());

        // 5명 있음.
        Assertions.assertEquals(5, userSerivce.getAllUsers());

        // 2명 삭제.
        userSerivce.deleteByName("Tom");
        userSerivce.deleteByName("Mike");

        // 아직 5명 있을걸?
        Assertions.assertEquals(3, userSerivce.getAllUsers());
    }

}

테스트 코드 실행 결과

디비테이블 확인 2개 추가 된걸 확인 할수 있다.

  • user 현재 테이블

  • flyway_schema_history : flyway가 관리하고 있는 테이블. 해당 테이블에 수행된 .sql 스크립트 내역들을 기재하고 있다.

위 내용을 이서 진행해보자.

만일 특정 개발자가 address 라는 컬럼을 테이블에 추가했다면 어떻게 될까?

ALTER TABLE `user` ADD COLUMN `address` VARCHAR(20) DEFAULT NULL;

스크립트 파일 명명 규칙은 버전번호_쿼리에 대한 설명 .sql 이다.

다시 테스트 코드를 돌리면 아래와 같은 수행완료 로그를 볼수 있다.

2022-12-26 16:58:12.025  INFO 37330 --- [           main] o.f.c.i.database.base.DatabaseType       : Database: jdbc:mysql://localhost:3306/test (MySQL 8.0)
2022-12-26 16:58:12.063  INFO 37330 --- [           main] o.f.core.internal.command.DbValidate     : Successfully validated 2 migrations (execution time 00:00.020s)
2022-12-26 16:58:12.075  INFO 37330 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema `test`: 1
2022-12-26 16:58:12.082  INFO 37330 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema `test` to version "1.1 - alter table user"
2022-12-26 16:58:12.113  INFO 37330 --- [           main] o.f.core.internal.command.DbMigrate      : Successfully applied 1 migration to schema `test` (execution time 00:00.045s)

테이블을 확인해보자

마찬가리로 history 테이블에도 아래와 같이 내역이 추가되었다.

https://flywaydb.org/