Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Dropwizard Migrations
3.
Adding Bundle
4.
Defining Migrations
5.
Working on the Database
5.1.
Checking Database’s State 
5.2.
Dumping the Schema 
5.3.
Tagging the Schema 
5.4.
Migrating the Schema 
5.5.
Rollback the Schema
5.6.
Testing Migration 
5.7.
Preparing Rollback Script
5.8.
Dumping the objects
6.
Support For Adding Multiple Migration Bundles
7.
Frequently Asked Questions
7.1.
What is Dropwizard? 
7.2.
What are the different database states?
7.3.
Name the libraries gathered in Dropwizard.
7.4.
What is a liquibase database?
7.5.
What is bootstrap in Dropwizard?
8.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Dropwizard Migrations

Author Ayushi Goyal
0 upvote

Introduction

Dropwizard is a lightweight RESTful Java framework. It is based on the Jetty app server, Jersey REST framework, and Jackson JSON parser. Yammer developed Dropwizard. It supports JVM(Java Virtual Machine) based backend. It provides the best Java libraries to embed in your applications. Dropwizard Migration is one of the modules of Dropwizard. 

Introduction

In this article, we will be discussing the dropwizard migration module. And how to work on the database using this module.  

Dropwizard Migrations

The dropwizard migration module provides a wrapper for refracting liquibase databases. Liquibase is an open-source platform. It enables you to create changes in the database. It supports various databases and file formats for defining the Database structure. 

Liquibase database

To configure the migration module class, you need to embed the following code. 

public class Configure extends Configuration {
    @Valid
    @NotNull
    private DataSourceFactory db = new DataSourceFactory();

    @JsonProperty("database")
    public DataSourceFactory getDB() {
        return db;
    }
}


Explanation - 

  • A 'Configure' class in the above code extends the 'Configuration' (pre-defined class). 
  • To configure the migration module, you need a DataSourceFactory object. So, we created a DataSourceFactory object named 'db'. 
  • Then we have created a method 'getDB()' that will return the DataSourceFactory object.
  • DataSourceFactory encapsulates the creation of a particular data source. For example, Hikari is the JDBC(Java Database Connectivity) data source.

Adding Bundle

To add a new migration bundle, you must add the following code in the 'initialize' method.

public class Configure extends Configuration {
    @Valid
    @NotNull
    private DataSourceFactory db = new DataSourceFactory();

    @JsonProperty("database")
    public DataSourceFactory getDB() {
        return db;
    }
}


Explanation - 

  • Override the 'initialize' method.
  • Use the 'addBundle' method to add the migration bundle. Pass the object of the MigrationBundle class(pre-defined class) to it.
  • Override the 'getDB()' method and return the DataSourceFactory object.

Migrate large database

To make large data migration, register and retrieve ‘SessionFactory’ in the ‘CustomChange’ method. 

@Override
public Map<String, Object> getObjects() 
{
    Map<String, Object> m = new HashMap<>();
    m.put("Example session", hibernateBundle.getSessionFactory());
    return m;
}

public void execute(Database db) throws CustomChangeException {
    Scope.getCurrentScope().get("Example session", SessionFactory.class);
}


GetObjects() method stores the session name and session factory in a map. The 'getSessionFactory()' method returns the session factory. W can then return the map.

Invoke the ‘execute’ method for retrieving the SessionFactory.

Defining Migrations

The ‘migration.xml’ file contains the dropwizard migration of your project. For example, if you want to create a 'student' table, your migration.xml will look like this. 

Create xml

<?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="coding_ninjas">
        <createTable tableName="student">
            <column name="RollNumber" type="int" autoIncrement="true">
            <constraints primaryKey="true" nullable="false"/>
            </column>

            <column name="StudentName" type="varchar(255)">
            <constraints nullable="false"/>
            </column>

            <column name="Course" type="varchar(255)">
            <constraints nullable="false"/>
            </column>
        </createTable>
    </changeSet>
</databaseChangeLog>
?>


This .xml file contains a student table having three-row. All rows must be non-empty, so set the nullable constraint to false. 

Working on the Database

Dropwizard migration module helps in retracting liquibase databases. Various operations performed are: 

Checking Database’s State 

To check the database state, the â€˜db status’ command. 

java -jar <jar-file>.jar db status <db-name>.yml


Here replace <jar-file> with your jar file name and <db-name> with your database name. 

JAR files are Java Archive files packed in zip format. It is a collection of many java files and their associated resources and metadata. 

There are various database states mentioned below:

Check state

State

Availability

Online

The Database is available to use and is functioning. 

Offline

The Database is not available to use and is not functioning. 

Restore

The database is unavailable as the user initiates the database restore process. 

Suspect

Due to some error during the recovery process database becomes unavailable. It is then set to suspect mode. 

Recovery

The Database is in the recovery process. It is set to online mode if done; otherwise set to suspect mode. 

Emergency

This state is set by the user or database administrator for safety. 

Recovery pending

This state arrives when the recovery process is in progress. The user then needs to perform an action to complete the process.  

 

Dumping the Schema 

Dump schema

Use the 'db dump' command to dump an existing schema in your database.

java -jar <jar-file>.jar db dump <db-name>.yml


Here replace <jar-file> with your jar file name and <db-name> with your database name. 

This command will produce a Liquibase change log. Using this log you can recreate your database. 

Tagging the Schema 

Add tag

To put a tag in your schema at a particular point, you can use the ‘db tag’ command. This makes the rollback operation easy. 

java -jar  <jar-file>.jar db tag <db-name>.yml <date> - <previous_move>


Here replace 

  • <jar-file> with your jar file name. 
  • <db-name> with your database name. 
  • <date> with the date you want to put a tag. The date should be in YYYY-MM-DD format. 
  • <previous_move> with the last user move. 

Migrating the Schema 

Migrating the schema means applying the pending change to your database. This can be done using the ‘db migrate’ command. 

java -jar <jar-file>.jar db migrate <db-name>.yml


Here replace <jar-file> with your jar file name and <db-name> with your database name. 

The changes done will be irreversible. 

Rollback the Schema

rollback

Use the 'db rollback' command to roll back the already applied changes. For this, you need to mention the date, tag, or the number of changes to roll back. 

java -jar <jar-file>.jar db migrate <db-name>.yml –<tag> <date>-<previous_move>


Here replace 

  • <jar-file> with your jar file name.
  • <db-name> with your database name.
  • <tag> with a created tag.
  • <date> with the date you want to put a tag. The date should be in YYYY-MM-DD format. 
  • <previous_move> with the last user move. 

The changes done will be irreversible. 

Testing Migration 

test migrations

The ‘db test’ command is used to check if a set of pending changes can be rolled back fully or not.

java -jar <jar-file>.jar db test <db-name>.yml


Here replace <jar-file> with your jar file name and <db-name> with your database name. 

Preparing Rollback Script

PREPARE SCRIPTS

To create a rollback script of the pending change, use the 'db prepare-rollback' command. 

java -jar <jar-file>.jar db prepare-rollback <db-name>.yml


Here replace <jar-file> with your jar file name and <db-name> with your database name. 

This will result in a DDL(Data Definition Language) script of all unapplied changes. 

Dumping the objects

DUMP OBJECTS

To drop all the database objects, call  The 'db drop-all' command. Along with this command, you need to specify '--confirm-delete-everything'. As this command will delete every object so, confirmation is necessary. 

java -jar <jar-file>.jar db drop-all --confirm-delete-everything <db-name>.yml


Here replace <jar-file> with your jar file name and <db-name> with your database name. 

Support For Adding Multiple Migration Bundles

We need two different data source factories to perform migration on two different databases. To do so, follow the below-mentioned steps.

Create two different data source factories. 

public class Configure extends Configuration {
    @Valid
    @NotNull
    private DataSourceFactory source1 = new DataSourceFactory();

    @Valid
    @NotNull
    private DataSourceFactory source2 = new DataSourceFactory();

    @JsonProperty("database source 1")
    public DataSourceFactory getSource1() {
        return source1;
    }

    @JsonProperty("database source 2")
    public DataSourceFactory getSource2() {
        return source2;
    }
}


Give unique names to both migration bundles.

@Override
public void initialize(Bootstrap<Configure> bootstrap) {
    bootstrap.addBundle(new MigrationsBundle<Configure>() {
        @Override
        public DataSourceFactory getDB(Configure c) {
            return c.getSource1();
        }

        @Override
        public String name() {
            // Return name of 1st migration bundle
            return "Database1";
        }
    });

    bootstrap.addBundle(new MigrationsBundle<Configure>() {
        @Override
        public DataSourceFactory getDB(Configure c) {
            return c.getSource2();
        }

        @Override
        public String name() {
            // Return name of 2nd migration bundle
            return "Database2";
        }
    });
}


Migrate the schema using the ‘db migrate’ command. 

java -jar index.jar Database1 migrate index.yml
java -jar index.jar Database2 migrate index.yml

This was all about Dropwizard Migration. Let's now discuss some of the frequently asked questions related to our topic. 

FAQ

Frequently Asked Questions

What is Dropwizard? 

Dropwizard is an open-source framework of Java. It is used for the fast development of high-performance RESTful web services. 

What are the different database states?

There are a total of seven states in the database. These are: online, offline, recovery, restore, suspect, emergency, and recovery pending.

Name the libraries gathered in Dropwizard.

Dropwizard gathers many popular libraries. These are Jersey, Jackson, Jetty, JUnit, Guava, etc,. These libraries enable the creation of lightweight packages. Furthermore, it uses its own library called Metrics.

What is a liquibase database?

Liquibase is an open-source platform using which you can create changes in the database. It supports various databases and file formats for defining the database structure. 

What is bootstrap in Dropwizard?

The bootstrap is a pre-start (temporary) application environment. It contains all of the components needed to bootstrap a Dropwizard command.

Conclusion 

This article contains basic information about the Dropwizard Migration module. In this article, we have discussed how to define and test migration. Along with the discussion of working on the database using the dropwizard migration module. The reader can carry out a thorough understanding of the topic by referring to the Official Documentation. For more information, Refer-

Check out the Coding Ninjas Website, Android DevelopmentCoding Ninjas Studio ProblemsCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas CoursesCoding Ninjas Studio Contests, and Coding Ninjas Studio Test Series for more excellent content. Do upvote our blog to assist other ninjas in their development. 

Good Luck!

Live masterclass