看看本身的項目的那些SQL文件或者乾脆連個建表語句都沒有的同窗是否會有想法把他們管理起來呢?向你們推薦一款很是輕量級的敏捷數據庫遷移框架——Flyway。想知道她有什麼魅力嗎?html
Flyway爲你們提供了以下的實現方式:java
Java APImysql
命令行sql
Maven數據庫
Gradleapache
Antsegmentfault
SBTapi
爲了減小描述難度在這裏使用了Java API,項目構建方式爲Maven,數據庫爲MySQLoracle
首先咱們要在命令行中使用Maven原型插件執行以下命令
mvn archetype:generate -B \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DarchetypeArtifactId=maven-archetype-quickstart \ -DarchetypeVersion=1.1 \ -DgroupId=foo \ -DartifactId=bar \ -Dversion=1.0-SNAPSHOT \ -Dpackage=foobar
咱們已經準備好開始了。當前項目的結構以下
. |-- pom.xml `-- src |-- main | `-- java | `-- foobar | `-- App.java `-- test `-- java `-- foobar `-- AppTest.java
進入建立的項目
cd bar
編輯當前目錄下的pom.xml
,增長Flyway和MySQL的依賴
<project ...> ... <dependencies> <dependency> <groupId>com.googlecode.flyway</groupId> <artifactId>flyway-core</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> ... </dependencies> ... </project>
如今咱們能夠將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(); } }
建立數據遷移目錄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) );
執行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).
假如咱們如今須要增長第二個數據遷移,命名爲: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).
經過Flyway讓咱們能很方便的管理數據庫文件,並進行版本控制。文檔地址