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;
}
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());
}
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();
}
}
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();
}
});
}
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);
}
}
Aggregations