Example usage for org.hibernate.boot Metadata getSessionFactoryBuilder

List of usage examples for org.hibernate.boot Metadata getSessionFactoryBuilder

Introduction

In this page you can find the example usage for org.hibernate.boot Metadata getSessionFactoryBuilder.

Prototype

SessionFactoryBuilder getSessionFactoryBuilder();

Source Link

Document

Get the builder for org.hibernate.SessionFactory instances based on this metamodel,

Usage

From source file:com.booleanworks.peacockmantisshrimp.modules.hibernate.mongodbogm.HibernateOgmBootstapper.java

public boolean bootstrap() throws OgmHelperException {

    this.checkConfigurationAndUpdateStatus();

    if (this.getStatus() != Status.goodConfiguration) {
        Logger.getLogger(this.getClass().getCanonicalName()).log(Level.SEVERE,
                "Bootstrapper seems to be in a bad configuration... aborting.");
        return false;
    }/* www  . j a v a  2s . c om*/

    if (this.getStatus() == Status.bootstrapping) {
        throw new OgmHelperException("already bootstrapping  !!");
    }

    this.setStatus(Status.bootstrapping);

    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();

    //And specific config
    ssrb.applySetting(OgmProperties.ENABLED, true);

    //assuming you are using JTA in a non container environment
    //ssrb.applySetting(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta");
    //assuming JBoss TransactionManager in standalone mode
    //ssrb.applySetting(AvailableSettings.JTA_PLATFORM, "JBossTS");
    //Using provided settings
    ssrb.applySettings(this.getSettings());

    if (this.getSettings().containsKey(OgmProperties.DATASTORE_PROVIDER)) {
        String providerValue = (String) this.getSettings().get(OgmProperties.DATASTORE_PROVIDER);

        if (providerValue.toLowerCase().equals("mongodb")) {
            Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO,
                    "Detecting MongoDb provider.... doing additional checks");
            if (!this.getSettings().containsKey(MongoDBProperties.AUTHENTICATION_MECHANISM)) {
                AuthenticationMechanismType authenticationMechanismType = AuthenticationMechanismType.SCRAM_SHA_1;

                Logger.getLogger(this.getClass().getCanonicalName()).log(Level.WARNING,
                        "No MongoDb authentication mecanism set, patching configuration, setting to "
                                + authenticationMechanismType.name());
                this.getSettings().put(MongoDBProperties.AUTHENTICATION_MECHANISM, authenticationMechanismType);

                Logger.getLogger(this.getClass().getCanonicalName()).log(Level.WARNING,
                        "Current setings are: " + this.getSettings().toString());
            }
        }

    }

    //saving ssrb
    this.setStandardServiceRegistryBuilder(ssrb);

    //building registry
    StandardServiceRegistry registry = ssrb.build();
    if (registry == null) {
        throw new OgmHelperException("Failed to get a registry !!");
    }

    //saving registry
    this.setStandardServiceRegistry(registry);

    MetadataSources ms = new MetadataSources(registry);

    for (Class cEntity : this.getDeclaredEntities()) {
        ms.addAnnotatedClass(cEntity);
        Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO,
                "Added entity: " + cEntity.getCanonicalName());
    }

    Metadata md = ms.buildMetadata(registry);

    SessionFactoryBuilder sfb = md.getSessionFactoryBuilder();

    OgmSessionFactory osf = sfb.unwrap(OgmSessionFactoryBuilder.class).build();

    //Saving the MetadataSources
    this.setMetadataSources(ms);

    //Saving SessionFactoryBuilder
    this.setSessionFactoryBuilder(sfb);

    //Savinf the OgmSessionFactory 
    this.setOgmSessionFactory(osf);

    this.setStatus(Status.ready);

    return true;
}

From source file:com.leaf.cashier.Utility.HibernateUtil.java

public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        try {// www . j av a 2  s  .  c  o m
            // Properties properties = new Properties();
            // properties.load(new FileInputStream(CommonConstant.HIBERNATE_PROPERTIES_FILE_PATH));
            registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

            //                Map<String, String> settings = new HashMap<>();
            //                settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
            //                settings.put(Environment.URL, "jdbc:mysql://127.0.0.1:3306/cashier");
            //                settings.put(Environment.USER, "root");
            //                settings.put(Environment.PASS, "");
            //                settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");
            //                settings.put(Environment.POOL_SIZE, "1");
            //                settings.put(Environment.FORMAT_SQL, "true");
            //                settings.put(Environment.SHOW_SQL, "true");
            //
            //                registryBuilder.applySettings(settings);
            //                registry = registryBuilder.build();
            MetadataSources sources = new MetadataSources(registry);
            Metadata metadata = sources.getMetadataBuilder().build();
            sessionFactory = metadata.getSessionFactoryBuilder().build();

        } catch (Exception e) {
            e.printStackTrace();
            if (registry != null) {
                StandardServiceRegistryBuilder.destroy(registry);
            }
        }

    }
    return sessionFactory;
}

From source file:com.projekt.kino.config.HibernateUtils.java

private static SessionFactory buildSessionFactory() {
    try {//  www  .  j  a  va2  s.  co m
        // Create the ServiceRegistry from hibernate.cfg.xml
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()//
                .configure("hibernate.cfg.xml").build();

        // Create a metadata sources using the specified service registry.
        Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();

        return metadata.getSessionFactoryBuilder().build();
    } catch (Throwable ex) {

        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.yahoo.elide.standalone.Util.java

License:Apache License

/**
 * Retrieve a hibernate session factory.
 *
 * @param hibernate5ConfigPath File path to hibernate config (i.e. hibernate-cfg.xml)
 * @param modelPackageName Name of package containing all models to be loaded by hibernate
 * @return Hibernate session factory./*from w w  w  .  j  a va2s  . c o m*/
 */
public static SessionFactory getSessionFactory(String hibernate5ConfigPath, String modelPackageName) {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
            .configure(new File(hibernate5ConfigPath)).build();
    MetadataSources sources = new MetadataSources(standardRegistry);

    getAllEntities(modelPackageName).forEach(sources::addAnnotatedClass);

    Metadata metaData = sources.getMetadataBuilder().build();
    return metaData.getSessionFactoryBuilder().build();
}

From source file:databaseManager.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {//from w ww  . ja v a2s . c o m
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
        return metadata.getSessionFactoryBuilder().build();

    } catch (HibernateException he) {
        System.out.println("Session Factory creation failure");
        throw he;
    }
}

From source file:Helpers.HibernateUtil.java

public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
        sessionFactory = metadata.getSessionFactoryBuilder().build();
    }//from  www . j  a v  a 2s  .  co  m
    return sessionFactory;
}

From source file:it.unitn.elisco.utils.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {//  w  w w.  j a  va  2 s  .  c  o m
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .applySetting("hibernate.hikari.dataSource.url",
                        ConfigurationProperties.getInstance().getDbURL())
                .applySetting("hibernate.hikari.dataSource.user",
                        ConfigurationProperties.getInstance().getDbUsername())
                .applySetting("hibernate.hikari.dataSource.password",
                        ConfigurationProperties.getInstance().getDbPassword())
                .configure("hibernate.cfg.xml").build();

        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();

        return metadata.getSessionFactoryBuilder().build();
    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:org.kitodo.data.database.persistence.HibernateUtil.java

License:Open Source License

/**
 * Retrieve current SessionFactory.//from  w  w w  .  j  a  v a 2  s .com
 *
 * @return SessionFactory
 */
private static SessionFactory getSessionFactory() {
    if (Objects.isNull(sessionFactory)) {
        try {
            registry = new StandardServiceRegistryBuilder().configure().build();
            MetadataSources sources = new MetadataSources(registry);
            Metadata metadata = sources.getMetadataBuilder().build();
            sessionFactory = metadata.getSessionFactoryBuilder().build();
        } catch (RuntimeException e) {
            shutdown();
            throw new HibernateException(e.getMessage(), e);
        }
    }
    return sessionFactory;
}

From source file:org.openflexo.connie.hbn.HbnConfig.java

License:Open Source License

public SessionFactory getSessionFactory() {

    if (sessionFactory == null) {
        Metadata metadata = getMetadata();

        final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();

        sessionFactory = sessionFactoryBuilder.build();
    } else {/*from  ww  w . j a v a  2  s.  c o m*/
        LOGGER.warning("Session Factory has already been built");
    }

    return sessionFactory;
}

From source file:to.etc.domui.hibernate.config.HibernateConfigurator.java

License:Open Source License

/**
 * Main worker to initialize the database layer, using Hibernate, with a user-specified core data source. This
 * code also enables SQL logging when .developer.properties option hibernate.sql=true.
 */// ww w  . j  av  a  2 s  .  co  m
public synchronized static void initialize(final DataSource ds) throws Exception {
    System.setProperty("org.jboss.logging.provider", "slf4j"); // Thanks to https://stackoverflow.com/questions/11639997/how-do-you-configure-logging-in-hibernate-4-to-use-slf4j
    if (m_sessionFactory != null)
        throw new IllegalStateException("HibernateConfigurator has already been initialized!");
    if (m_annotatedClassList.size() == 0)
        throw new IllegalStateException(
                "Please call addClasses(Class<?>...) and register your Hibernate data classes before calling me.");

    long ts = System.nanoTime();
    m_dataSource = ds;

    // see https://www.boraji.com/hibernate-5-event-listener-example

    //-- Create Hibernate's config. See https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/bootstrap/Bootstrap.html
    /*
     * Hibernate apparently cannot initialize without the useless hibernate.cfg.xml file. We cannot
     * add that file at the root location because that would interfere with applications. To have a
     * working model we add it as a resource in this class's package. And of course Hibernate makes
     * it hard to reach- we need to calculate the proper name, sigh.
     */
    BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder()
            .applyIntegrator(new JpaIntegrator()).build();

    String resname = "/" + HibernateConfigurator.class.getPackage().getName().replace('.', '/')
            + "/hibernate.cfg.xml";
    StandardServiceRegistryBuilder serviceBuilder = new StandardServiceRegistryBuilder(bootstrapRegistry)
            .configure(resname);

    /*
     * Set other properties according to config settings made.
     */
    serviceBuilder.applySetting("hibernate.connection.datasource", ds);
    boolean logsql;
    if (m_showSQL == null)
        logsql = DeveloperOptions.getBool("hibernate.sql", false); // Take default from .developer.properties
    else
        logsql = m_showSQL.booleanValue();

    if (logsql) {
        serviceBuilder.applySetting("show_sql", "true");
        serviceBuilder.applySetting("hibernate.show_sql", "true");
    }

    /*
     * Hibernate defaults to completely non-standard behavior for sequences, using the
     * "hilo" sequence generator by default. This irresponsible behavior means that
     * by default Hibernate code is incompatible with any code using sequences.
     * Since that is irresponsible and downright DUMB this reverts the behavior to
     * using sequences in their normal behavior.
     * See https://stackoverflow.com/questions/12745751/hibernate-sequencegenerator-and-allocationsize
     */
    serviceBuilder.applySetting("hibernate.id.new_generator_mappings", "true"); // MUST BE BEFORE config.configure

    m_hibernateOptions.forEach((option, value) -> serviceBuilder.applySetting(option, value));

    if (DeveloperOptions.getBool("hibernate.format_sql", true)) {
        serviceBuilder.applySetting("hibernate.format_sql", "true");
    }

    switch (m_mode) {
    default:
        throw new IllegalStateException("Mode: " + m_mode);
    case CREATE:
        serviceBuilder.applySetting("hbm2ddl.auto", "create");
        serviceBuilder.applySetting("hibernate.hbm2ddl.auto", "create");
        break;
    case NONE:
        serviceBuilder.applySetting("hbm2ddl.auto", "none");
        serviceBuilder.applySetting("hibernate.hbm2ddl.auto", "none");
        break;
    case UPDATE:
        serviceBuilder.applySetting("hbm2ddl.auto", "update");
        serviceBuilder.applySetting("hibernate.hbm2ddl.auto", "update");
        break;
    }

    // change settings
    for (IHibernateConfigListener listener : m_onConfigureList) {
        listener.onSettings(serviceBuilder);
    }

    ServiceRegistry reg = serviceBuilder.build();
    MetadataSources sources = new MetadataSources(reg);

    for (Class<?> clz : m_annotatedClassList)
        sources.addAnnotatedClass(clz);

    // add classes
    for (IHibernateConfigListener listener : m_onConfigureList) {
        listener.onAddSources(sources);
    }

    Metadata metaData = sources.getMetadataBuilder()
            .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();

    enhanceMappings(metaData);

    //for(Consumer<Configuration> listener : m_onConfigureList) {
    //   listener.accept(config);
    //}

    //-- Create the session factory: this completes the Hibernate config part.
    SessionFactoryBuilder sessionFactoryBuilder = metaData.getSessionFactoryBuilder();

    //      sessionFactoryBuilder.applyInterceptor( new CustomSessionFactoryInterceptor() );

    //sessionFactoryBuilder.addSessionFactoryObservers( new CustomSessionFactoryObserver() );

    // Apply a CDI BeanManager ( for JPA event listeners )
    //sessionFactoryBuilder.applyBeanManager( getBeanManager() );

    SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) sessionFactoryBuilder.build();
    m_sessionFactory = sessionFactory;

    EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry()
            .getService(EventListenerRegistry.class);
    if (m_beforeImagesEnabled) {
        // https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/events/Events.html
        listenerRegistry.prependListeners(EventType.POST_LOAD, new CreateBeforeImagePostLoadListener());
        listenerRegistry.prependListeners(EventType.INIT_COLLECTION, new CopyCollectionEventListener());
    }
    for (IHibernateConfigListener listener : m_onConfigureList) {
        listener.onAddListeners(listenerRegistry);
    }

    //-- Start DomUI/WebApp.core initialization: generalized database layer
    HibernateSessionMaker hsm;
    if (m_beforeImagesEnabled) {
        //-- We need the copy interceptor to handle these.
        hsm = dc -> {
            return m_sessionFactory.withOptions().interceptor(new BeforeImageInterceptor(dc.getBeforeCache()))
                    .openSession();
            //return m_sessionFactory.openSession(new BeforeImageInterceptor(dc.getBeforeCache()));
        };
    } else {
        hsm = dc -> m_sessionFactory.openSession();
    }

    //-- If no handlers are registered: register the default ones.
    if (m_handlers.size() == 0) {
        m_handlers.register(JdbcQueryExecutor.FACTORY);
        m_handlers.register(HibernateQueryExecutor.FACTORY);
    }

    m_contextSource = new HibernateLongSessionContextFactory(m_listeners, hsm, m_handlers);
    System.out.println("domui: Hibernate initialization took a whopping "
            + StringTool.strNanoTime(System.nanoTime() - ts));
}