Search in sources :

Example 6 with ConnectionProvider

use of org.hibernate.engine.jdbc.connections.spi.ConnectionProvider in project hibernate-orm by hibernate.

the class ConnectionProviderInitiator method initiateService.

@Override
public ConnectionProvider initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
    final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy(configurationValues);
    if (strategy == MultiTenancyStrategy.DATABASE || strategy == MultiTenancyStrategy.SCHEMA) {
        // nothing to do, but given the separate hierarchies have to handle this here.
        return null;
    }
    final StrategySelector strategySelector = registry.getService(StrategySelector.class);
    final Object explicitSetting = configurationValues.get(AvailableSettings.CONNECTION_PROVIDER);
    if (explicitSetting != null) {
        // if we are explicitly supplied a ConnectionProvider to use (in some form) -> use it..
        if (explicitSetting instanceof ConnectionProvider) {
            return (ConnectionProvider) explicitSetting;
        } else if (explicitSetting instanceof Class) {
            final Class providerClass = (Class) explicitSetting;
            LOG.instantiatingExplicitConnectionProvider(providerClass.getName());
            return instantiateExplicitConnectionProvider(providerClass);
        } else {
            String providerName = StringHelper.nullIfEmpty(explicitSetting.toString());
            if (providerName != null) {
                if (LEGACY_CONNECTION_PROVIDER_MAPPING.containsKey(providerName)) {
                    final String actualProviderName = LEGACY_CONNECTION_PROVIDER_MAPPING.get(providerName);
                    DeprecationLogger.DEPRECATION_LOGGER.connectionProviderClassDeprecated(providerName, actualProviderName);
                    providerName = actualProviderName;
                }
                LOG.instantiatingExplicitConnectionProvider(providerName);
                final Class providerClass = strategySelector.selectStrategyImplementor(ConnectionProvider.class, providerName);
                try {
                    return instantiateExplicitConnectionProvider(providerClass);
                } catch (Exception e) {
                    throw new HibernateException("Could not instantiate connection provider [" + providerName + "]", e);
                }
            }
        }
    }
    if (configurationValues.get(AvailableSettings.DATASOURCE) != null) {
        return new DatasourceConnectionProviderImpl();
    }
    ConnectionProvider connectionProvider = null;
    final Class<? extends ConnectionProvider> singleRegisteredProvider = getSingleRegisteredProvider(strategySelector);
    if (singleRegisteredProvider != null) {
        try {
            connectionProvider = singleRegisteredProvider.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            throw new HibernateException("Could not instantiate singular-registered ConnectionProvider", e);
        }
    }
    if (connectionProvider == null) {
        if (c3p0ConfigDefined(configurationValues)) {
            connectionProvider = instantiateC3p0Provider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (proxoolConfigDefined(configurationValues)) {
            connectionProvider = instantiateProxoolProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (hikariConfigDefined(configurationValues)) {
            connectionProvider = instantiateHikariProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (viburConfigDefined(configurationValues)) {
            connectionProvider = instantiateViburProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (agroalConfigDefined(configurationValues)) {
            connectionProvider = instantiateAgroalProvider(strategySelector);
        }
    }
    if (connectionProvider == null) {
        if (configurationValues.get(AvailableSettings.URL) != null) {
            connectionProvider = new DriverManagerConnectionProviderImpl();
        }
    }
    if (connectionProvider == null) {
        LOG.noAppropriateConnectionProvider();
        connectionProvider = new UserSuppliedConnectionProviderImpl();
    }
    final Map injectionData = (Map) configurationValues.get(INJECTION_DATA);
    if (injectionData != null && injectionData.size() > 0) {
        final ConnectionProvider theConnectionProvider = connectionProvider;
        new BeanInfoHelper(connectionProvider.getClass()).applyToBeanInfo(connectionProvider, new BeanInfoHelper.BeanInfoDelegate() {

            public void processBeanInfo(BeanInfo beanInfo) throws Exception {
                final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor descriptor : descriptors) {
                    final String propertyName = descriptor.getName();
                    if (injectionData.containsKey(propertyName)) {
                        final Method method = descriptor.getWriteMethod();
                        method.invoke(theConnectionProvider, injectionData.get(propertyName));
                    }
                }
            }
        });
    }
    return connectionProvider;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) HibernateException(org.hibernate.HibernateException) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method) StrategySelector(org.hibernate.boot.registry.selector.spi.StrategySelector) HibernateException(org.hibernate.HibernateException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) MultiTenancyStrategy(org.hibernate.MultiTenancyStrategy) BeanInfoHelper(org.hibernate.internal.util.beans.BeanInfoHelper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with ConnectionProvider

use of org.hibernate.engine.jdbc.connections.spi.ConnectionProvider in project hibernate-orm by hibernate.

the class ViburDBCPConnectionProviderTest method testSelectStatementWithStatementsCache.

@Test
public void testSelectStatementWithStatementsCache() {
    setUpPoolAndDatabase(1, 10);
    ConnectionProvider cp = sessionFactory().getServiceRegistry().getService(ConnectionProvider.class);
    ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource();
    ConcurrentMap<StatementMethod, StatementHolder> mockedStatementCache = mockStatementCache(ds);
    doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect);
    // We set above the poolMaxSize = 1, that's why the second session will get and use the same underlying connection.
    doInHibernate(this::sessionFactory, ViburDBCPConnectionProviderTest::executeAndVerifySelect);
    InOrder inOrder = inOrder(mockedStatementCache);
    inOrder.verify(mockedStatementCache).get(key1.capture());
    inOrder.verify(mockedStatementCache).putIfAbsent(same(key1.getValue()), val1.capture());
    inOrder.verify(mockedStatementCache).get(key2.capture());
    assertEquals(1, mockedStatementCache.size());
    assertTrue(mockedStatementCache.containsKey(key1.getValue()));
    assertEquals(key1.getValue(), key2.getValue());
    assertEquals(AVAILABLE, val1.getValue().state().get());
}
Also used : InOrder(org.mockito.InOrder) StatementMethod(org.vibur.dbcp.stcache.StatementMethod) ViburDBCPDataSource(org.vibur.dbcp.ViburDBCPDataSource) StatementHolder(org.vibur.dbcp.stcache.StatementHolder) ViburDBCPConnectionProvider(org.hibernate.vibur.internal.ViburDBCPConnectionProvider) ViburDBCPConnectionProvider(org.hibernate.vibur.internal.ViburDBCPConnectionProvider) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) Test(org.junit.Test)

Example 8 with ConnectionProvider

use of org.hibernate.engine.jdbc.connections.spi.ConnectionProvider in project jOOQ by jOOQ.

the class Setup method run.

// This class sets up an EntityManager and configures the jOOQ DSLContext
// ----------------------------------------------------------------------
static void run(BiConsumer<EntityManager, DSLContext> consumer) throws Exception {
    Connection connection = null;
    EntityManagerFactory emf = null;
    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).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());
        Map<Object, Object> props = new HashMap<>();
        DataSource ds = new SingleConnectionDataSource(connection);
        props.put("hibernate.connection.datasource", ds);
        props.put("hibernate.archive.autodetection", "");
        emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(pui(ds), props);
        em = emf.createEntityManager();
        final EntityManager e = em;
        // Run some Hibernate / jOOQ logic inside of a transaction
        em.getTransaction().begin();
        data(em);
        consumer.accept(em, new DefaultConfiguration().set(connection).set(onStart(ctx -> e.flush())).dsl());
        em.getTransaction().commit();
    } finally {
        if (em != null)
            em.close();
        if (emf != null)
            emf.close();
        if (connection != null)
            connection.close();
    }
}
Also used : LoggingConnection(org.jooq.tools.jdbc.LoggingConnection) Language(org.jooq.example.jpa.entity.Language) Arrays(java.util.Arrays) Connection(java.sql.Connection) URL(java.net.URL) AvailableSettings(org.hibernate.cfg.AvailableSettings) PersistenceUnitTransactionType(jakarta.persistence.spi.PersistenceUnitTransactionType) HashMap(java.util.HashMap) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Film(org.jooq.example.jpa.entity.Film) ValidationMode(jakarta.persistence.ValidationMode) ExecuteListener.onStart(org.jooq.ExecuteListener.onStart) Title(org.jooq.example.jpa.embeddables.Title) SQLException(java.sql.SQLException) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) DataSource(javax.sql.DataSource) DSLContext(org.jooq.DSLContext) ClassTransformer(jakarta.persistence.spi.ClassTransformer) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) EnumSet(java.util.EnumSet) SharedCacheMode(jakarta.persistence.SharedCacheMode) TargetType(org.hibernate.tool.schema.TargetType) LoggingConnection(org.jooq.tools.jdbc.LoggingConnection) Properties(java.util.Properties) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) IOException(java.io.IOException) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PersistenceUnitInfo(jakarta.persistence.spi.PersistenceUnitInfo) MetadataSources(org.hibernate.boot.MetadataSources) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) HibernatePersistenceProvider(org.hibernate.jpa.HibernatePersistenceProvider) Year(java.time.Year) EntityManager(jakarta.persistence.EntityManager) Actor(org.jooq.example.jpa.entity.Actor) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) Collections(java.util.Collections) DriverManager(java.sql.DriverManager) SingleConnectionDataSource(org.jooq.tools.jdbc.SingleConnectionDataSource) SingleConnectionDataSource(org.jooq.tools.jdbc.SingleConnectionDataSource) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) SQLException(java.sql.SQLException) HashMap(java.util.HashMap) Connection(java.sql.Connection) LoggingConnection(org.jooq.tools.jdbc.LoggingConnection) MetadataSources(org.hibernate.boot.MetadataSources) HibernatePersistenceProvider(org.hibernate.jpa.HibernatePersistenceProvider) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) DataSource(javax.sql.DataSource) SingleConnectionDataSource(org.jooq.tools.jdbc.SingleConnectionDataSource) EntityManager(jakarta.persistence.EntityManager) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport)

Example 9 with ConnectionProvider

use of org.hibernate.engine.jdbc.connections.spi.ConnectionProvider in project hibernate-orm by hibernate.

the class MultiTenancyTest method configureStandardServiceRegistryBuilder.

@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
    super.configureStandardServiceRegistryBuilder(ssrb);
    ssrb.addService(MultiTenantConnectionProvider.class, new AbstractMultiTenantConnectionProvider() {

        @Override
        protected ConnectionProvider getAnyConnectionProvider() {
            return db1;
        }

        @Override
        protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
            if (DB1.equals(tenantIdentifier))
                return db1;
            if (DB2.equals(tenantIdentifier))
                return db2;
            throw new IllegalArgumentException();
        }
    });
}
Also used : AbstractMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider) AbstractMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider) XaConnectionProvider(org.hibernate.test.cache.infinispan.tm.XaConnectionProvider) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) MultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider)

Example 10 with ConnectionProvider

use of org.hibernate.engine.jdbc.connections.spi.ConnectionProvider in project hibernate-orm by hibernate.

the class TableGeneratorQuotingTest method testTableGeneratorQuoting.

@Test
@TestForIssue(jiraKey = "HHH-7927")
public void testTableGeneratorQuoting() {
    final Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(TestEntity.class).buildMetadata();
    final ConnectionProvider connectionProvider = serviceRegistry.getService(ConnectionProvider.class);
    final GenerationTarget target = new GenerationTargetToDatabase(new DdlTransactionIsolatorTestingImpl(serviceRegistry, new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess(connectionProvider)));
    new SchemaCreatorImpl(serviceRegistry).doCreation(metadata, false, target);
    try {
        new SchemaValidator().validate(metadata);
    } catch (HibernateException e) {
        fail("The identifier generator table should have validated.  " + e.getMessage());
    } finally {
        new SchemaDropperImpl(serviceRegistry).doDrop(metadata, false, target);
    }
}
Also used : DdlTransactionIsolatorTestingImpl(org.hibernate.test.util.DdlTransactionIsolatorTestingImpl) SchemaCreatorImpl(org.hibernate.tool.schema.internal.SchemaCreatorImpl) SchemaDropperImpl(org.hibernate.tool.schema.internal.SchemaDropperImpl) HibernateException(org.hibernate.HibernateException) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) SchemaValidator(org.hibernate.tool.hbm2ddl.SchemaValidator) GenerationTarget(org.hibernate.tool.schema.internal.exec.GenerationTarget) GenerationTargetToDatabase(org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Aggregations

ConnectionProvider (org.hibernate.engine.jdbc.connections.spi.ConnectionProvider)19 Test (org.junit.Test)11 Connection (java.sql.Connection)8 Properties (java.util.Properties)5 SQLException (java.sql.SQLException)4 IOException (java.io.IOException)3 Map (java.util.Map)3 MetadataSources (org.hibernate.boot.MetadataSources)3 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)3 Configurable (org.hibernate.service.spi.Configurable)3 Startable (org.hibernate.service.spi.Startable)3 Stoppable (org.hibernate.service.spi.Stoppable)3 DdlTransactionIsolatorTestingImpl (org.hibernate.test.util.DdlTransactionIsolatorTestingImpl)3 TestForIssue (org.hibernate.testing.TestForIssue)3 Method (java.lang.reflect.Method)2 ResultSet (java.sql.ResultSet)2 Statement (java.sql.Statement)2 HashMap (java.util.HashMap)2 DataSource (javax.sql.DataSource)2 HibernateException (org.hibernate.HibernateException)2