还有一些用于迁移的工具,例如java中的rails。
Liquibase,Flyway,MyBatis迁移等等。
这次,我之前解释过的Dropwizard包括Liquibase,因此我想使用该示例进行解释。
顺便说一下,Liquibase和Flyway之间的区别是在这里以易于理解的方式编写的。
概述
用一个词来解释Liquibase,它是"用于管理DB模式中的更改的工具"。
随着开发敏捷,代码将稳定地变化,并且数据库模式也会以相同的方式变化。
在这种情况下,如果没有这样的工具,更改可能会很麻烦,会减慢开发速度,在最坏的情况下,由于您不想更改产品,导致产品向错误的方向发展。
如果您无法灵活,快速地发展,那将是当今无法生存的工具。
模式更改历史记录可以用以下格式描述。
- XML格式
- YAML
- JSON格式
- 的SQL
- 其他(Groovy,Clojure)
然后,您可以点击命令以获取目标版本。当然,您可以还原到以前的版本。
另外,由于它不依赖于数据库产品,因此您可以决定以后使用哪种数据库产品,并且可以轻松地对其进行更改。
前提
这是先前环境的延续。
我将其添加到上一个示例中。
Maven设置
由于这是一个示例,因此我们将使用嵌入式DB h2数据库。
使用另一个DB时,请使目标JDBC驱动程序依赖。
依靠dropwizard-migrations进行迁移。
pom.xml
1 2 3 4 5 6 7 8 9 10 11 | <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-migrations</artifactId> <version>${dropwizard.version}</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.175</version> </dependency> |
配置类
DataSourceFactory将是与yaml的数据库部分相对应的Dropwizard Configuration类。
这是因为它是一种设计策略,建议对配置文件和Configuration类进行分组以使Dropwizard易于管理。
HelloWorldConfiguration.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Valid @NotNull private DataSourceFactory database = new DataSourceFactory(); @JsonProperty("database") public DataSourceFactory getDataSourceFactory() { return database; } @JsonProperty("database") public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.database = dataSourceFactory; } |
example.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Database settings. database: # the name of your JDBC driver driverClass: org.h2.Driver # the username user: sa # the password password: sa # the JDBC URL url: jdbc:h2:target/example |
应用类别
注册MigrationsBundle类。这是Dropwizard提供的抽象类。
HelloWorldApplication.java
1 2 3 4 5 6 7 8 9 10 11 12 | @Override public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) { ??? bootstrap.addBundle(new MigrationsBundle<HelloWorldConfiguration>() { @Override public DataSourceFactory getDataSourceFactory( HelloWorldConfiguration configuration) { return configuration.getDataSourceFactory(); } }); ??? } |
建立表格
Liquibase XML
首先,用xml编写以创建表。
src / main /资源/ migrations.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?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="ko2ic"> <createTable tableName="people"> <column name="id" type="bigint" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <column name="fullName" type="varchar(255)"> <constraints nullable="false"/> </column> <column name="jobTitle" type="varchar(255)"/> </createTable> </changeSet> </databaseChangeLog> |