Example usage for org.hibernate.boot MetadataSources getMetadataBuilder

List of usage examples for org.hibernate.boot MetadataSources getMetadataBuilder

Introduction

In this page you can find the example usage for org.hibernate.boot MetadataSources getMetadataBuilder.

Prototype

public MetadataBuilder getMetadataBuilder() 

Source Link

Document

Get a builder for metadata where non-default options can be specified.

Usage

From source file:com.fitbur.testify.fixture.common.SessionFactoryFactoryBean.java

License:Apache License

@Override
public SessionFactory getObject() throws Exception {
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .loadProperties("hibernate.properties").applySetting(Environment.DATASOURCE, dataSource).build();

    Reflections reflections = new Reflections(DatabaseConfig.class.getPackage().getName());
    MetadataSources metadataSources = new MetadataSources(registry);

    MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
            .applyPhysicalNamingStrategy(new PhysicalNamingStrategyStandardImpl())
            .applyImplicitNamingStrategy(new ImplicitNamingStrategyComponentPathImpl());

    reflections.getSubTypesOf(AttributeConverter.class).parallelStream()
            .forEach(metadataBuilder::applyAttributeConverter);

    reflections.getTypesAnnotatedWith(Entity.class).parallelStream()
            .forEach(metadataSources::addAnnotatedClass);

    Metadata metadata = metadataBuilder.build();

    return metadata.buildSessionFactory();
}

From source file:com.fitbur.testify.fixture.PostgresDockerConfig.java

License:Apache License

@Bean
FactoryBean<SessionFactory> sessionFactoryImplProvider(DataSource dataSource) {
    return new SmartFactoryBean<SessionFactory>() {
        @Override/*from w  w w  . j a  v a  2s.com*/
        public boolean isPrototype() {
            return false;
        }

        @Override
        public boolean isEagerInit() {
            return true;
        }

        @Override
        public SessionFactory getObject() throws Exception {
            StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                    .loadProperties("hibernate.properties").applySetting(Environment.DATASOURCE, dataSource)
                    .build();

            Reflections reflections = new Reflections(PostgresDockerConfig.class.getPackage().getName());
            MetadataSources metadataSources = new MetadataSources(registry);

            MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
                    .applyPhysicalNamingStrategy(new PhysicalNamingStrategyStandardImpl())
                    .applyImplicitNamingStrategy(new ImplicitNamingStrategyComponentPathImpl());

            reflections.getSubTypesOf(AttributeConverter.class).parallelStream()
                    .forEach(metadataBuilder::applyAttributeConverter);

            reflections.getTypesAnnotatedWith(Entity.class).parallelStream()
                    .forEach(metadataSources::addAnnotatedClass);

            Metadata metadata = metadataBuilder.build();

            return metadata.buildSessionFactory();
        }

        @Override
        public Class<?> getObjectType() {
            return SessionFactory.class;
        }

        @Override
        public boolean isSingleton() {
            return true;
        }
    };

}

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

public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        try {/*from  ww w .  ja v a 2  s.co  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.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.//www  . ja  v  a2s  . 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:com.zeroone.guestebook.domain.SchemaGenerator.java

License:Apache License

public SchemaGenerator(String packageName, Dialect dialect) throws Exception {
    BootstrapServiceRegistry bsr;/* w  ww . j av a2 s  .c o  m*/
    bsr = new BootstrapServiceRegistryBuilder().build();
    StandardServiceRegistryBuilder ssrBuilder;
    ssrBuilder = new StandardServiceRegistryBuilder(bsr);
    ssrBuilder.applySetting("hibernate.dialect", dialect.dialectClass);
    ServiceRegistry serviceRegistry = ssrBuilder.build();
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    for (Class<?> clazz : getClasses(packageName)) {
        metadataSources.addAnnotatedClass(clazz);
    }
    MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
    this.metadata = (MetadataImplementor) metadataBuilder.build();
    this.dialect = dialect;
}

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

License:Open Source License

/**
 * Retrieve current SessionFactory./* www. j av a2 s.  c o m*/
 *
 * @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: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.
 *///w  w w . j  a v  a  2  s  . c  om
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));
}