Step 1 :創建Changelog文件,所有的數據庫變動都會保存在Changelog文件中
<?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> </databaseChangeLog>
Step 2:添加數據庫變動(對應於Changelog文件中的changeSet元素)
每一個ChangeSet元素都是通過id,author,文件名,包全限定名來唯一標識。如果只指定了id屬性,那么在有多個人協同開發並且存在多個分支的時候很容易造成ChangeSet重復。
將每一個changeSet都看做你想要應用到數據庫的一個原子操作,通常在一個ChangeSet中最好只包含一個變化,但是如果你想在一個事務中插入多條記錄,將它們放在一個ChangeSet中效果會非常好。Liquibase會嘗試將每個changeSet放在一個事務中執行,但是很多數據庫可能會靜默的提交事務,或者為某些命令如(create table,drop table,等)開啟新的事物。
<?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> <changeSet id="1" author="bob"> <createTable tableName="department"> <column name="id" type="int"> <constraints primaryKey="true" nullable="false"/> </column> <column name="name" type="varchar(50)"> <constraints nullable="false"/> </column> <column name="active" type="boolean" defaultValueBoolean="true"/> </createTable> </changeSet> </databaseChangeLog>
Step 3:運行ChangeSet
有很多方式都可以運行change log 包括: via command line, Ant, Maven, Spring, a servlet listener, and a CDI Environment.
一個mysql通過jdbc運行的例子:
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
Step 4:檢查你的數據庫
你會發現你的數據庫中多了一個"department"表。而且還創建了兩張其它的表“databasechangelog” 和 “databasechangeloglock”。“databasechangelog”表包含了在這個數據庫中已經執行的所有的語法的列表。“databasechangeloglock”用了確保兩個機器不會嘗試在同一時刻修改數據庫。