All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.leanix.dropkit.persistence.PersistenceModule Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
package net.leanix.dropkit.persistence;

import com.google.inject.Provides;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.db.DatabaseConfiguration;
import io.dropwizard.migrations.DbCommand;
import io.dropwizard.setup.Environment;
import org.hibernate.SessionFactory;
import ru.vyarus.dropwizard.guice.module.support.DropwizardAwareModule;

/**
 * Guice module for persistence.
 *
 *
 * @param 
 */
public class PersistenceModule extends DropwizardAwareModule
    implements DatabaseConfiguration {

    private DropkitHibernateBundle hibernateBundle;
    private boolean hibernateBundleInitialized = false;

    /**
     * Pass the hibernate bundle to the constructor.
     *
     * new PersistenceModule(A.class, B.class, C.class)
     *
     * @param hibernateBundle
     */
    public PersistenceModule(DropkitHibernateBundle hibernateBundle) {
        super();
        this.hibernateBundle = hibernateBundle;
    }

    /**
     * Provides the session factory for DAO objects.
     *
     * @param configuration
     * @param environment
     * @return
     * @throws java.lang.Exception
     */
    @SuppressWarnings("unchecked")
    @Provides
    public SessionFactory provideSessionFactory(Configuration configuration, Environment environment) throws Exception {
        // Because the hibernate bundle needs to be initialized lazily, we will do this the first time
        // the SessionFactory is requested.
        if (!hibernateBundleInitialized) {
            hibernateBundle.run((T) configuration, environment);
            hibernateBundleInitialized = true;
        }

        return hibernateBundle.getSessionFactory();
    }

    // @Provides
    @SuppressWarnings("unchecked")
    public DbCommand getMigrationsCommand() {
        return new DbCommand<>("db", this, (Class) this.configuration().getClass(), null);
    }

    /**
     * This method is required for the migration db command (module implements
     * DatabaseConfiguration).
     *
     * @param t
     * @return
     */
    @Override
    public DataSourceFactory getDataSourceFactory(T t) {
        return t.getDataSourceFactory();
    }

    public void run(Environment environment, SessionFactory factory) {
        environment.healthChecks().register("database", new DatabaseHealthCheck(factory));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy