Example usage for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder

List of usage examples for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder

Introduction

In this page you can find the example usage for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder.

Prototype

public StandardServiceRegistryBuilder() 

Source Link

Document

Create a default builder.

Usage

From source file:org.infinispan.test.hibernate.cache.util.CacheTestUtil.java

License:LGPL

public static StandardServiceRegistryBuilder buildBaselineStandardServiceRegistryBuilder(String regionPrefix,
        Class regionFactory, boolean use2ndLevel, boolean useQueries,
        Class<? extends JtaPlatform> jtaPlatform) {
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();

    ssrb.applySettings(//w  w  w. ja v a2  s.c o m
            buildBaselineSettings(regionPrefix, regionFactory, use2ndLevel, useQueries, jtaPlatform));

    return ssrb;
}

From source file:org.jasypt.hibernate5.test.TestHibernateTypes.java

License:Apache License

private void initialize() {
    registerEncryptors();/*w w w .j  av  a2 s  .  c  o  m*/

    // Configure Hibernate and open session
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
            .applySetting("hibernate.connection.url", "jdbc:hsqldb:mem:jasypttestdb")
            .applySetting("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.connection.pool_size", "10").build();

    //      BootstrapServiceRegistry serviceRegistryBuilder = new StandardServiceRegistryBuilder()
    //          .applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
    //            .applySetting("hibernate.connection.url",
    //                "jdbc:hsqldb:mem:jasypttestdb")
    //            .applySetting("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
    //            .applySetting("hibernate.connection.username", "sa")
    //            .applySetting("hibernate.connection.password", "")
    //            .applySetting("hibernate.connection.pool_size", "10");
    //      ServiceRegistry serviceRegistry = serviceRegistryBuilder();

    hbConf = new Configuration();
    sessionFactory = hbConf.addClass(User.class)
            .setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
            .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:jasypttestdb")
            .setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
            .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
            .setProperty("hibernate.connection.pool_size", "10").buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();

    initDB();

    generateData();
}

From source file:org.jboss.as.test.integration.hibernate.SFSBHibernatewithCriteriaSession.java

License:Open Source License

public void setupConfig() {
    // static {//w  w  w  .ja  v a  2 s.  c  om
    try {

        // prepare the configuration
        Configuration configuration = new Configuration()
                .setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
        configuration.getProperties().put(AvailableSettings.JTA_PLATFORM, JBossAppServerJtaPlatform.class);
        configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
        configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS");
        configuration.setProperty("hibernate.listeners.envers.autoRegister", "false");

        // fetch the properties
        Properties properties = new Properties();
        configuration = configuration.configure("hibernate.cfg.xml");
        properties.putAll(configuration.getProperties());

        Environment.verifyProperties(properties);
        ConfigurationHelper.resolvePlaceHolders(properties);

        // build the serviceregistry
        StandardServiceRegistryBuilder registry = new StandardServiceRegistryBuilder()
                .applySettings(properties);
        sessionFactory = configuration.buildSessionFactory(registry.build());

        // build metamodel
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
        MetamodelImpl.buildMetamodel(configuration.getClassMappings(), sfi);

        sessionFactory.getStatistics().setStatisticsEnabled(true);

    } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        // ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }

}

From source file:org.jboss.as.test.integration.hibernate.SFSBHibernatewithMetaDataSession.java

License:Open Source License

public void setupConfig() {
    // static {/* w w  w .j  a  va 2  s  .c om*/
    try {

        // prepare the configuration
        Configuration configuration = new Configuration()
                .setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
        configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
        configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS");
        configuration.setProperty("hibernate.listeners.envers.autoRegister", "false");

        // fetch the properties
        Properties properties = new Properties();
        configuration = configuration.configure("hibernate.cfg.xml");
        properties.putAll(configuration.getProperties());

        Environment.verifyProperties(properties);
        ConfigurationHelper.resolvePlaceHolders(properties);

        StandardServiceRegistryBuilder registry = new StandardServiceRegistryBuilder()
                .applySettings(properties);
        sessionFactory = configuration.buildSessionFactory(registry.build());

        // build metamodel
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
        MetamodelImpl.buildMetamodel(configuration.getClassMappings(), sfi);

        sessionFactory.getStatistics().setStatisticsEnabled(true);

    } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        // ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }

}

From source file:org.jooq.example.jpa.JPAExample.java

License:Apache License

@SuppressWarnings("serial")
public static void main(String[] args) throws Exception {
    Connection connection = null;
    EntityManagerFactory emf = null;//www .  jav a  2s.  c om
    EntityManager em = null;

    try {

        // Bootstrapping JDBC:
        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection("jdbc:h2:mem:jooq-jpa-example", "sa", "");
        final Connection c = connection;

        // Creating an in-memory H2 database from our entities
        MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
                .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
                .applySetting("javax.persistence.schema-generation-connection", connection)
                .applySetting("javax.persistence.create-database-schemas", true)

                // [#5607] JPADatabase causes warnings - This prevents
                // them
                .applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {
                    @SuppressWarnings("rawtypes")
                    @Override
                    public boolean isUnwrappableAs(Class unwrapType) {
                        return false;
                    }

                    @Override
                    public <T> T unwrap(Class<T> unwrapType) {
                        return null;
                    }

                    @Override
                    public Connection getConnection() {
                        return c;
                    }

                    @Override
                    public void closeConnection(Connection conn) throws SQLException {
                    }

                    @Override
                    public boolean supportsAggressiveRelease() {
                        return true;
                    }
                }).build());

        metadata.addAnnotatedClass(Actor.class);
        metadata.addAnnotatedClass(Film.class);
        metadata.addAnnotatedClass(Language.class);

        SchemaExport export = new SchemaExport();
        export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());

        // Setting up an EntityManager using Spring (much easier than out-of-the-box Hibernate)
        LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabasePlatform(SQLDialect.H2.thirdParty().hibernateDialect());
        bean.setDataSource(new SingleConnectionDataSource(connection, true));
        bean.setPackagesToScan("org.jooq.example.jpa.entity");
        bean.setJpaVendorAdapter(adapter);
        bean.setPersistenceUnitName("test");
        bean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        bean.afterPropertiesSet();

        emf = bean.getObject();
        em = emf.createEntityManager();

        final EntityManager e = em;

        // Run some Hibernate / jOOQ logic inside of a transaction
        em.getTransaction().begin();
        run(em, DSL.using(new DefaultConfiguration().set(connection).set(new DefaultExecuteListener() {
            @Override
            public void start(ExecuteContext ctx) {
                // Flush all changes from the EntityManager to the database for them to be visible in jOOQ
                e.flush();
                super.start(ctx);
            }
        })));
        em.getTransaction().commit();
    } finally {
        if (em != null)
            em.close();

        if (emf != null)
            emf.close();

        if (connection != null)
            connection.close();
    }
}

From source file:org.jooq.example.jpa.Setup.java

License:Apache License

static void run(BiConsumer<EntityManager, DSLContext> consumer) throws Exception {
    Connection connection = null;
    EntityManagerFactory emf = null;//w  w w  . java  2 s  .  c  om
    EntityManager em = null;

    try {

        // Bootstrapping JDBC:
        Class.forName("org.h2.Driver");
        connection = new LoggingConnection(
                DriverManager.getConnection("jdbc:h2:mem:jooq-jpa-example", "sa", ""));
        final Connection c = connection;

        // Creating an in-memory H2 database from our entities
        MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
                .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
                .applySetting("javax.persistence.schema-generation-connection", connection)
                .applySetting("javax.persistence.create-database-schemas", true)

                // [#5607] JPADatabase causes warnings - This prevents
                // them
                .applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {
                    @SuppressWarnings("rawtypes")
                    @Override
                    public boolean isUnwrappableAs(Class unwrapType) {
                        return false;
                    }

                    @Override
                    public <T> T unwrap(Class<T> unwrapType) {
                        return null;
                    }

                    @Override
                    public Connection getConnection() {
                        return c;
                    }

                    @Override
                    public void closeConnection(Connection conn) throws SQLException {
                    }

                    @Override
                    public boolean supportsAggressiveRelease() {
                        return true;
                    }
                }).build());

        metadata.addAnnotatedClass(Actor.class);
        metadata.addAnnotatedClass(Film.class);
        metadata.addAnnotatedClass(Language.class);

        SchemaExport export = new SchemaExport();
        export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());

        // Setting up an EntityManager using Spring (much easier than out-of-the-box Hibernate)
        LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabasePlatform(SQLDialect.H2.thirdParty().hibernateDialect());
        bean.setDataSource(new SingleConnectionDataSource(connection, true));
        bean.setPackagesToScan("org.jooq.example.jpa.entity");
        bean.setJpaVendorAdapter(adapter);
        bean.setPersistenceUnitName("test");
        bean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        bean.afterPropertiesSet();

        emf = bean.getObject();
        em = emf.createEntityManager();

        final EntityManager e = em;

        // Run some Hibernate / jOOQ logic inside of a transaction
        em.getTransaction().begin();
        data(em);

        consumer.accept(em,
                DSL.using(new DefaultConfiguration().set(connection).set(new DefaultExecuteListener() {
                    @Override
                    public void start(ExecuteContext ctx) {
                        // Flush all changes from the EntityManager to the database for them to be visible in jOOQ
                        e.flush();
                        super.start(ctx);
                    }
                })));
        em.getTransaction().commit();
    } finally {
        if (em != null)
            em.close();

        if (emf != null)
            emf.close();

        if (connection != null)
            connection.close();
    }
}

From source file:org.jooq.meta.extensions.jpa.JPADatabase.java

License:Apache License

@Override
protected DSLContext create0() {
    if (connection == null) {
        String packages = getProperties().getProperty("packages");

        if (isBlank(packages)) {
            packages = "";
            log.warn("No packages defined",
                    "It is highly recommended that you provide explicit packages to scan");
        }/*  w  w w.  j  a v a2  s  . co m*/

        // [#9058] Properties use camelCase notation.
        boolean useAttributeConverters = Boolean.valueOf(getProperties().getProperty("useAttributeConverters",
                getProperties().getProperty("use-attribute-converters", "true")));
        String unqualifiedSchema = getProperties().getProperty("unqualifiedSchema", "none").toLowerCase();
        publicIsDefault = "none".equals(unqualifiedSchema);

        try {
            Properties info = new Properties();
            info.put("user", "sa");
            info.put("password", "");
            connection = new org.h2.Driver().connect("jdbc:h2:mem:jooq-meta-extensions-" + UUID.randomUUID(),
                    info);

            // [#6709] Apply default settings first, then allow custom overrides
            Map<String, Object> settings = new LinkedHashMap<>();
            settings.put("hibernate.dialect", HIBERNATE_DIALECT);
            settings.put("javax.persistence.schema-generation-connection", connection);
            settings.put("javax.persistence.create-database-schemas", true);

            // [#5607] JPADatabase causes warnings - This prevents them
            settings.put(AvailableSettings.CONNECTION_PROVIDER, connectionProvider());

            for (Entry<Object, Object> entry : getProperties().entrySet()) {
                String key = "" + entry.getKey();

                if (key.startsWith("hibernate.") || key.startsWith("javax.persistence."))
                    userSettings.put(key, entry.getValue());
            }
            settings.putAll(userSettings);

            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
            builder.applySettings(settings);

            MetadataSources metadata = new MetadataSources(builder.applySettings(settings).build());

            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                    true);

            scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

            // [#5845] Use the correct ClassLoader to load the jpa entity classes defined in the user project
            ClassLoader cl = Thread.currentThread().getContextClassLoader();

            for (String pkg : packages.split(","))
                for (BeanDefinition def : scanner.findCandidateComponents(defaultIfBlank(pkg, "").trim()))
                    metadata.addAnnotatedClass(Class.forName(def.getBeanClassName(), true, cl));

            // This seems to be the way to do this in idiomatic Hibernate 5.0 API
            // See also: http://stackoverflow.com/q/32178041/521799
            // SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
            // export.create(true, true);

            // Hibernate 5.2 broke 5.0 API again. Here's how to do this now:
            SchemaExport export = new SchemaExport();
            export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());

            if (useAttributeConverters)
                loadAttributeConverters(metadata.getAnnotatedClasses());
        } catch (Exception e) {
            throw new DataAccessException("Error while exporting schema", e);
        }
    }

    return DSL.using(connection);
}

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

License:Open Source License

/**
 * Retrieve current SessionFactory./*from   w w w  .j a  v  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:org.lncc.martin.ct.dao.hibernate.HibernateUtil.java

License:Open Source License

public Session getConnection() {

    try {//from  w w w .j av  a  2  s.  com
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");

        StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();
        sb.applySettings(cfg.getProperties());

        StandardServiceRegistry standardServiceRegistry = sb.build();

        sessionFactory = cfg.buildSessionFactory(standardServiceRegistry);

        return sessionFactory.openSession();

    } catch (Exception e) {
        System.out.println("Problemas ao criar Session Factory: " + e);
        return null;
    }
}

From source file:org.n52.sos.config.sqlite.SQLiteSessionFactory.java

License:Open Source License

private SessionFactory createSessionFactory(Properties properties) {
    Configuration cfg = new Configuration().addAnnotatedClass(BooleanSettingValue.class)
            .addAnnotatedClass(FileSettingValue.class).addAnnotatedClass(IntegerSettingValue.class)
            .addAnnotatedClass(NumericSettingValue.class).addAnnotatedClass(StringSettingValue.class)
            .addAnnotatedClass(UriSettingValue.class).addAnnotatedClass(ChoiceSettingValue.class)
            .addAnnotatedClass(AdminUser.class).addAnnotatedClass(CapabilitiesExtensionImpl.class)
            .addAnnotatedClass(OfferingExtensionImpl.class).addAnnotatedClass(StaticCapabilitiesImpl.class)
            .addAnnotatedClass(Operation.class).addAnnotatedClass(ProcedureEncoding.class)
            .addAnnotatedClass(Binding.class).addAnnotatedClass(ObservationEncoding.class)
            .addAnnotatedClass(DynamicOfferingExtension.class)
            .addAnnotatedClass(DynamicOwsExtendedCapabilities.class)
            .addAnnotatedClass(TimeInstantSettingValue.class)
            .addAnnotatedClass(MultilingualStringSettingValue.class);

    cfg.registerTypeOverride(new HibernateFileType(), new String[] { "file", File.class.getName() });
    cfg.registerTypeOverride(new HibernateUriType(), new String[] { "uri", URI.class.getName() });
    cfg.registerTypeOverride(new HibernateTimeInstantType(),
            new String[] { "timeInstant", TimeInstant.class.getName() });

    if (properties != null) {
        cfg.mergeProperties(properties);
    }/*ww w .jav  a  2s .c  om*/
    cfg.mergeProperties(defaultProperties);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
            .build();
    return cfg.buildSessionFactory(serviceRegistry);
}