Fork me on GitHub

Flyway Tutorial

This tutorial demonstrates initialising the database with Flyway.

The following migration script is used to set up the database:

CREATE TABLE MIGRATION (
  ID BIGINT IDENTITY PRIMARY KEY,
  MESSAGE VARCHAR(50)
);

INSERT INTO MIGRATION ( MESSAGE ) VALUES ( 'MIGRATED' );

With the following end point retrieving data from the setup database:

	public void getMigration(@HttpQueryParameter("id") String migrationId, EntityManager entityManager,
			ObjectResponse<Migration> responder) {
		responder.send(entityManager.find(Migration.class, Long.parseLong(migrationId)));
	}

Tutorial Source

Flyway migration

To have Flyway migrate the database on start up, add the following dependency:

		<dependency>
			<groupId>net.officefloor.persistence</groupId>
			<artifactId>officeflyway_migrate</artifactId>
		</dependency>

Ensuring there is a DataSource configured, e.g.:

	<managed-object source="net.officefloor.jdbc.DataSourceManagedObjectSource">
		<property-file path="datasource.properties" />
	</managed-object>

That's it. On startup, OfficeFloor will load Flyway and migrate the DataSource's database.

Testing

H2 in memory instances can be used to mock databases for testing. To ease resetting the database between tests the following dependency can be added:

		<dependency>
			<groupId>net.officefloor.persistence</groupId>
			<artifactId>officejdbc_h2_test</artifactId>
			<scope>test</scope>
		</dependency>

This will allowing injecting the following dependency that uses Flyway to reset the database between tests:

	@BeforeEach
	public void resetDatabase(H2Reset reset) {
		reset.reset();
	}

The following test then retrieves the setup data:

	@RegisterExtension
	public final MockWoofServerExtension server = new MockWoofServerExtension();

	@Test
	public void migrationAvailable() {
		MockWoofResponse response = this.server.send(MockWoofServer.mockRequest("/migration?id=1"));
		response.assertJson(200, new Migration(1L, "MIGRATED"));
	}

Next

The next tutorial covers using Reactive logic.