Flyway-使用步骤

 

1.创建一个Maven项目

2.编辑当下的pom.xml,添加flyway依赖和Mysql依赖

<project ...>
    ...
    <dependencies>
        <dependency>
            <groupId>com.googlecode.flyway</groupId>
            <artifactId>flyway-core</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        ...
    </dependencies>
    ...
</project>

3.整合flyway

  现在我们可以将Flyway的代码放入项目中,并配置数据库,例如增加到默认生成的:src/main/java/foobar/App.java

package foobar;

import com.googlecode.flyway.core.Flyway;

public class App {
    public static void main(String[] args) {
        // 创建Flyway实例
        Flyway flyway = new Flyway();

        // 设置数据库
        flyway.setDataSource("jdbc:mysql://localhost:3306/foobar", "user", "pass");

        // 开始迁移
        flyway.migrate();
    }
}

4.创建第一个数据迁移

  创建数据迁移目录src/main/resources/db/migration

  执行命令mkdir -p src/main/resources/db/migration

  创建我们的第一个数据迁移src/main/resources/db/migration/V1__Create_person_table.sql

CREATE TABLE person (
    id INT,
    name VARCHAR(100)
);

5.执行App.java

  执行App.java(也可以直接在IDE中执行main方法)

  mvn package exec:java -Dexec.mainClass=foobar.App -Dmaven.test.skip=true

  如果你成功了,应该会得到如下信息

INFO: Creating Metadata table: `foobar`.`schema_version`
Feb 27, 2014 12:20:18 AM com.googlecode.flyway.core.command.DbMigrate migrate
INFO: Current version of schema `foobar`: << Empty Schema >>
Feb 27, 2014 12:20:18 AM com.googlecode.flyway.core.command.DbMigrate applyMigration
INFO: Migrating schema `foobar` to version 1
Feb 27, 2014 12:20:18 AM com.googlecode.flyway.core.command.DbMigrate logSummary
INFO: Successfully applied 1 migration to schema `foobar` (execution time 00:00.194s).

6.继续添加数据迁移

  假如我们现在需要增加第二个数据迁移,命名为:src/main/resources/db/migration/V2__Add_people.sql

INSERT INTO person (id, name) VALUES (1, 'Axel');
INSERT INTO person (id, name) VALUES (2, 'Mr. Foo');
INSERT INTO person (id, name) VALUES (3, 'Ms. Bar');

  执行命令

  mvn package exec:java -Dexec.mainClass=foobar.App -Dmaven.test.skip=true

  输出如下

Feb 27, 2014 12:25:00 AM com.googlecode.flyway.core.command.DbMigrate migrate
INFO: Current version of schema `foobar`: 1
Feb 27, 2014 12:25:00 AM com.googlecode.flyway.core.command.DbMigrate applyMigration
INFO: Migrating schema `foobar` to version 2
Feb 27, 2014 12:25:00 AM com.googlecode.flyway.core.command.DbMigrate logSummary
INFO: Successfully applied 1 migration to schema `foobar` (execution time 00:00.047s).

 

posted @ 2016-01-11 12:42  CALLME熊大  阅读(2266)  评论(0编辑  收藏  举报