在頻繁的工程實踐中,服務端程式與資料庫不斷的更新,如果服務端和資料庫部署不一緻,經常性的會導緻各種問題。為了解決這一問題,可行的方案之一就是讓資料庫随着服務端的版本而更新,flyway就是一種解決方案。
一. 目的
管理資料庫更新。
二.方法
直接在java工程中嵌入sql腳本。工程重新部署時,會自動更新資料庫,保證資料庫與代碼同步,避免了手動更新資料庫帶來的弊病。
三.原理
在資料庫中建立了一個表schema_version,該表的最後記錄為目前資料庫版本。
四.步驟
1.在pom檔案中加入如下:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>3.2.1</version>
</dependency>
2.在dispatcher-servlet.xml中加入
<bean id="flyway" class="org.flywaydb.core.Flyway" depends-on="dataSource" lazy-init="false" init-method="migrate">
<property name="dataSource" ref="dataSource"/>
<property name="initOnMigrate" value="true" />
<property name="validateOnMigrate" value="false" />
</bean>
同時讓其它資料庫操作bean依賴于flyway這個bean,避免資料庫未更新完畢已經進行資料庫操作。
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" depends-on="flyway">
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" depends-on="flyway">
3.在resources下建立資料庫腳本更新目錄,請注意腳本命名方式

五.注意
1.flyway不支援復原,如果你增加了一個字段,然後又要删除這個字段,就隻能寫一個V2_6_0_1__Delete_new_like_Column.sql的腳本。
2.一旦使用flyway,就不要使用手動方式修改資料庫,同時不得删除schema_version中資料。