第一步:
創建一個Changelog File:
這個database Changelog file列舉了數據庫中所有的改變情況,該文件是以xml為基礎的,下面是一個空的xml文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <databaseChangeLog 4 xmlns="http://www.liquibase.org/xml/ns/dbchangelog" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog 7 http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> 8 9 </databaseChangeLog>
第二步:
增加一個變化集;
每一個變化集都是有id屬性和author屬性來唯一確定的,這兩個屬性隨着名字和Changelog文件來唯一確定哪些做出的變化,如果只用id來表明,由於id過於簡單將會導致一些覆蓋的產生;尤其是在很多開發者以及很多開發代碼分支中,包含author屬性可以盡力降低覆蓋的風險;
把每個你將要運用到你的數據庫上的變化集當成原子變化,在你的變化集合中最好只包含一個改變;或者是在包含很多個改變時,可以確保你插入的多行做為單一的操作,liquibase試圖盡力運行每個改變作為一次單一操作,但是很多數據庫都有默認的方式,我們可以恢復某些指令;
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <databaseChangeLog 4 xmlns="http://www.liquibase.org/xml/ns/dbchangelog" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog 7 http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> 8 9 <changeSet id="1" author="bob"> 10 <createTable tableName="department"> 11 <column name="id" type="int"> 12 <constraints primaryKey="true" nullable="false"/> 13 </column> 14 <column name="name" type="varchar(50)"> 15 <constraints nullable="false"/> 16 </column> 17 <column name="active" type="boolean" defaultValueBoolean="true"/> 18 </createTable> 19 </changeSet> 20 21 </databaseChangeLog>
第三步:
運行變化集
執行你的變化log有很多中方式,命令行,Ant, Maven, spring,一個servlet監聽和CDI環境;
下面是一個mysql下執行的例子:
liquibase --driver=com.mysql.jdbc.Driver \
--classpath=/path/to/classes \
--changeLogFile=com/example/db.changelog.xml \
--url="jdbc:mysql://localhost/example" \
--username=user \
--password=asdf \
migrate
現在liquibase支持很多數據庫,在數據庫的詳細類別和那些數據庫驅動,url 以及classpath,請參見http://www.liquibase.org/databases.html;
第四步:
檢查你的數據庫
你將會看到你的數據庫現在包含量一張名字為department的表,於此同時,還有兩張表也被創建了;databasechangelog和databasechangelogelock,在databasechangelog表中包含一系列的已經運行於數據庫的狀態;databasechangeloglock表被用來確保兩個機器不能同時改變數據庫;