Example usage for org.hibernate.cfg AvailableSettings CONNECTION_PROVIDER

List of usage examples for org.hibernate.cfg AvailableSettings CONNECTION_PROVIDER

Introduction

In this page you can find the example usage for org.hibernate.cfg AvailableSettings CONNECTION_PROVIDER.

Prototype

String CONNECTION_PROVIDER

To view the source code for org.hibernate.cfg AvailableSettings CONNECTION_PROVIDER.

Click Source Link

Document

Names the org.hibernate.engine.jdbc.connections.spi.ConnectionProvider to use for obtaining JDBC connections.

Usage

From source file:com.abcanthur.website.codegenhack.JPADatabase.java

License:Apache License

@SuppressWarnings("serial")
@Override/*from w  w w  . jav  a2  s  . c o  m*/
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");
        }

        try {
            connection = DriverManager.getConnection("jdbc:h2:mem:jooq-meta-extensions", "sa", "");

            MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
                    .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
                    .applySetting("javax.persistence.schema-generation-connection", connection)

                    // [#5607] JPADatabase causes warnings - This prevents them
                    .applySetting(AvailableSettings.CONNECTION_PROVIDER,
                            "com.abcanthur.website.codegenhack.CustomConnectionProvider")
                    .build());

            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                    true);

            scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
            for (String pkg : packages.split(","))
                for (BeanDefinition def : scanner.findCandidateComponents(defaultIfBlank(pkg, "").trim()))
                    metadata.addAnnotatedClass(Class.forName(def.getBeanClassName()));

            // 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());
        } catch (Exception e) {
            throw new DataAccessException("Error while exporting schema", e);
        }
    }

    return DSL.using(connection);
}

From source file:com.flipkart.fdp.migration.db.DBInitializer.java

License:Apache License

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put(DRIVER, config.getDbDriver());
    properties.put(USER, config.getDbUserName());
    properties.put(PASS, config.getDbUserPassword());
    properties.put(URL, config.getDbConnectionURL());
    properties.put(DIALECT, config.getDbDialect());
    // "org.hibernate.dialect.MySQL5Dialect"
    properties.put(SHOW_SQL, "false");
    properties.put(HBM2DDL_AUTO, "update");
    properties.put(CURRENT_SESSION_CONTEXT_CLASS, "thread");
    // properties.put("current_session_context_class", "thread");
    properties.put(RELEASE_CONNECTIONS, "after_transaction");

    properties.put(POOL_SIZE, 10);//from  ww  w  .ja  v  a 2  s  .  c o m
    properties.put(org.hibernate.cfg.AvailableSettings.CONNECTION_PROVIDER,
            "org.hibernate.connection.C3P0ConnectionProvider");
    properties.put(org.hibernate.cfg.AvailableSettings.C3P0_MAX_SIZE, 100);
    properties.put(org.hibernate.cfg.AvailableSettings.C3P0_MIN_SIZE, 5);
    properties.put(org.hibernate.cfg.AvailableSettings.C3P0_MAX_STATEMENTS, 0);
    properties.put(org.hibernate.cfg.AvailableSettings.C3P0_ACQUIRE_INCREMENT, 1);
    properties.put(org.hibernate.cfg.AvailableSettings.C3P0_IDLE_TEST_PERIOD, 100);
    properties.put(org.hibernate.cfg.AvailableSettings.C3P0_TIMEOUT, 100);

    return properties;
}

From source file:org.efaps.bpm.BPM.java

License:Apache License

/**
 * Initialize BPM.//from   www . j  a  v a 2 s  .  c  om
 *
 * @throws EFapsException on error
 */
public static void initialize() throws EFapsException {
    final SystemConfiguration config = EFapsSystemConfiguration.get();
    final boolean active = config != null ? config.getAttributeValueAsBoolean(KernelSettings.ACTIVATE_BPM)
            : false;
    if (active) {

        if (BPM.PMANAGER != null) {
            BPM.PMANAGER.close();
            BPM.PMANAGER = null;
        }
        if (BPM.SMANAGER != null) {
            BPM.SMANAGER.close();
            BPM.SMANAGER = null;
        }

        UserTransaction userTrans = null;
        InitialContext context = null;
        try {
            context = new InitialContext();
            userTrans = TransactionHelper.findUserTransaction();
            Object object = null;
            try {
                object = context.lookup(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME);
            } catch (final NamingException ex) {
                BPM.LOG.info("Checked for JtaTransactionManager");
            }
            if (object == null) {
                context.bind(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, userTrans);
                context.bind(JtaTransactionManager.FALLBACK_TRANSACTION_MANAGER_NAMES[0],
                        TransactionHelper.findTransactionManager());
            }
        } catch (final NamingException ex) {
            BPM.LOG.error("Could not initialise JNDI InitialContext", ex);
        }

        // register our own KnowledgeBuilderFactoryService
        ServiceRegistryImpl.getInstance().addDefault(KnowledgeBuilderFactoryService.class,
                KnowledgeBuilderFactoryServiceImpl.class.getName());

        final RegisterableItemsFactoryImpl itemsFactory = new RegisterableItemsFactoryImpl();
        itemsFactory.addWorkItemHandler("Manual Task", ManualTaskItemHandler.class);
        itemsFactory.addProcessListener(WorkingMemoryLogListener.class);

        final Map<String, String> properties = new HashMap<String, String>();
        properties.put(AvailableSettings.DIALECT, Context.getDbType().getHibernateDialect());
        properties.put(AvailableSettings.SHOW_SQL, String.valueOf(BPM.LOG.isDebugEnabled()));
        properties.put(AvailableSettings.FORMAT_SQL, "true");
        properties.put(AvailableSettings.RELEASE_CONNECTIONS, "after_transaction");
        properties.put(AvailableSettings.CONNECTION_PROVIDER, ConnectionProvider.class.getName());
        properties.put(org.hibernate.jpa.AvailableSettings.NAMING_STRATEGY, NamingStrategy.class.getName());

        final EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa",
                properties);

        final RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.getDefault()
                .classLoader(EFapsClassLoader.getInstance()).userGroupCallback(new UserGroupCallbackImpl())
                .entityManagerFactory(emf).registerableItemsFactory(itemsFactory).persistence(true)
                .addEnvironmentEntry("TRANSACTION_LOCK_ENABLED", "false");

        BPM.add2EnvironmentBuilder(builder);

        final RuntimeEnvironment environment = builder.get();
        final ManagerFactoryImpl factory = new ManagerFactoryImpl();

        BPM.PMANAGER = factory.newPerProcessInstanceRuntimeManager(environment);
        BPM.SMANAGER = factory.newSingletonRuntimeManager(environment);
    }
}

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;//from   w  w w .  j ava  2 s. co m
    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.  j  av  a  2 s.c o  m
    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.AttributeConverterExtractor.java

License:Apache License

private final EntityManagerFactory initEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
    Map<String, Object> configuration = new HashMap<>();
    configuration.put("hibernate.integrator_provider", integratorProvider());
    configuration.put(AvailableSettings.CONNECTION_PROVIDER, database.connectionProvider());
    PersistenceUnitInfoDescriptor descriptor = new PersistenceUnitInfoDescriptor(persistenceUnitInfo);
    return new EntityManagerFactoryBuilderImpl(descriptor, configuration).build();
}

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");
        }/*from   ww w . j  av  a  2  s .  c o 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);
}