Java Code Examples for org.hibernate.engine.jdbc.connections.spi.ConnectionProvider

The following examples show how to use org.hibernate.engine.jdbc.connections.spi.ConnectionProvider. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void mysqlConfiguration(StandardServiceRegistry registry) {
	registry.getService( ConnectionProvider.class ); //force the NoJdbcConnectionProvider to load first
	registry.getService( SchemaManagementTool.class )
			.setCustomDatabaseGenerationTarget( new ReactiveGenerationTarget(registry) {
				@Override
				public void prepare() {
					super.prepare();
					if ( dbType() == DBType.MYSQL ) {
						accept("set foreign_key_checks = 0");
					}
				}
				@Override
				public void release() {
					if ( dbType() == DBType.MYSQL ) {
						accept("set foreign_key_checks = 1");
					}
					super.release();
				}
			} );
}
 
Example 2
@Override
public ConnectionProvider resolve(String tenantId) {

    LOG.debugv("resolve({0})", tenantId);

    final MultiTenancyStrategy strategy = jpaConfig.getMultiTenancyStrategy();
    LOG.debugv("multitenancy strategy: {0}", strategy);
    AgroalDataSource dataSource = tenantDataSource(jpaConfig, tenantId, strategy);
    if (dataSource == null) {
        throw new IllegalStateException("No instance of datasource found for tenant: " + tenantId);
    }
    if (strategy == MultiTenancyStrategy.SCHEMA) {
        return new TenantConnectionProvider(tenantId, dataSource);
    }
    return new QuarkusConnectionProvider(dataSource);
}
 
Example 3
private static ConnectionProvider resolveConnectionProvider(String tenantIdentifier) {
    LOG.debugv("resolveConnectionProvider({0})", tenantIdentifier);
    InstanceHandle<TenantConnectionResolver> instance = Arc.container().instance(TenantConnectionResolver.class);
    if (!instance.isAvailable()) {
        throw new IllegalStateException(
                "No instance of " + TenantConnectionResolver.class.getSimpleName() + " was found. "
                        + "You need to create an implementation for this interface to allow resolving the current tenant connection.");
    }
    TenantConnectionResolver resolver = instance.get();
    ConnectionProvider cp = resolver.resolve(tenantIdentifier);
    if (cp == null) {
        throw new IllegalStateException("Method 'TenantConnectionResolver."
                + "resolve(String)' returned a null value. This violates the contract of the interface!");
    }
    return cp;
}
 
Example 4
Source Project: lams   Source File: SessionFactoryUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the DataSource of the given SessionFactory.
 * @param sessionFactory the SessionFactory to check
 * @return the DataSource, or {@code null} if none found
 * @see ConnectionProvider
 */
public static DataSource getDataSource(SessionFactory sessionFactory) {
	Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
	if (getProperties != null) {
		Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
		Object dataSourceValue = props.get(Environment.DATASOURCE);
		if (dataSourceValue instanceof DataSource) {
			return (DataSource) dataSourceValue;
		}
	}
	if (sessionFactory instanceof SessionFactoryImplementor) {
		SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
		try {
			ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
			if (cp != null) {
				return cp.unwrap(DataSource.class);
			}
		}
		catch (UnknownServiceException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
			}
		}
	}
	return null;
}
 
Example 5
private void releaseConnection() throws SQLException {
	if ( connection != null ) {
		try {
			serviceRegistry.getService( JdbcEnvironment.class ).getSqlExceptionHelper().logAndClearWarnings(
					connection );
		}
		finally {
			try {
				serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection );
			}
			finally {
				connection = null;
			}
		}
	}
}
 
Example 6
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private JdbcConnectionAccess buildLocalConnectionAccess() {
	return new JdbcConnectionAccess() {
		@Override
		public Connection obtainConnection() throws SQLException {
			return !settings.getMultiTenancyStrategy().requiresMultiTenantConnectionProvider()
					? serviceRegistry.getService( ConnectionProvider.class ).getConnection()
					: serviceRegistry.getService( MultiTenantConnectionProvider.class ).getAnyConnection();
		}

		@Override
		public void releaseConnection(Connection connection) throws SQLException {
			if ( !settings.getMultiTenancyStrategy().requiresMultiTenantConnectionProvider() ) {
				serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection );
			}
			else {
				serviceRegistry.getService( MultiTenantConnectionProvider.class ).releaseAnyConnection( connection );
			}
		}

		@Override
		public boolean supportsAggressiveRelease() {
			return false;
		}
	};
}
 
Example 7
@Override
public JdbcConnectionAccess getJdbcConnectionAccess() {
	// See class-level JavaDocs for a discussion of the concurrent-access safety of this method
	if ( jdbcConnectionAccess == null ) {
		if ( !factory.getSettings().getMultiTenancyStrategy().requiresMultiTenantConnectionProvider() ) {
			jdbcConnectionAccess = new NonContextualJdbcConnectionAccess(
					getEventListenerManager(),
					factory.getServiceRegistry().getService( ConnectionProvider.class )
			);
		}
		else {
			jdbcConnectionAccess = new ContextualJdbcConnectionAccess(
					getTenantIdentifier(),
					getEventListenerManager(),
					factory.getServiceRegistry().getService( MultiTenantConnectionProvider.class )
			);
		}
	}
	return jdbcConnectionAccess;
}
 
Example 8
Source Project: spring4-understanding   Source File: SessionFactoryUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determine the DataSource of the given SessionFactory.
 * @param sessionFactory the SessionFactory to check
 * @return the DataSource, or {@code null} if none found
 * @see ConnectionProvider
 */
public static DataSource getDataSource(SessionFactory sessionFactory) {
	if (sessionFactory instanceof SessionFactoryImplementor) {
		try {
			ConnectionProvider cp = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getService(
					ConnectionProvider.class);
			if (cp != null) {
				return cp.unwrap(DataSource.class);
			}
		}
		catch (UnknownServiceException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
			}
		}
	}
	return null;
}
 
Example 9
Source Project: gorm-hibernate5   Source File: GrailsHibernateTemplate.java    License: Apache License 2.0 6 votes vote down vote up
public GrailsHibernateTemplate(SessionFactory sessionFactory) {
    Assert.notNull(sessionFactory, "Property 'sessionFactory' is required");
    this.sessionFactory = sessionFactory;

    ConnectionProvider connectionProvider = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getService(ConnectionProvider.class);
    if(connectionProvider instanceof DatasourceConnectionProviderImpl) {
        this.dataSource = ((DatasourceConnectionProviderImpl) connectionProvider).getDataSource();
        if(dataSource instanceof TransactionAwareDataSourceProxy) {
            this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
        }
        jdbcExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dataSource);
    }
    else {
        // must be in unit test mode, setup default translator
        SQLErrorCodeSQLExceptionTranslator sqlErrorCodeSQLExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator();
        sqlErrorCodeSQLExceptionTranslator.setDatabaseProductName("H2");
        jdbcExceptionTranslator = sqlErrorCodeSQLExceptionTranslator;
    }
}
 
Example 10
Source Project: unitime   Source File: HibernateUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void closeHibernate() {
	if (sSessionFactory!=null) {
		if (sSessionFactory instanceof SessionFactoryImpl) {
			ConnectionProvider cp = ((SessionFactoryImpl)sSessionFactory).getConnectionProvider();
			if (cp instanceof DisposableConnectionProvider) {
				try {
					((DisposableConnectionProvider)cp).destroy();
				} catch (Exception e) {
					sLog.error("Failed to destroy connection provider: " + e.getMessage());
				}
			}
		}
		sSessionFactory.close();
		sSessionFactory=null;
	}
}
 
Example 11
Source Project: spring-analysis-note   Source File: SessionFactoryUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Determine the DataSource of the given SessionFactory.
 * @param sessionFactory the SessionFactory to check
 * @return the DataSource, or {@code null} if none found
 * @see ConnectionProvider
 */
@Nullable
public static DataSource getDataSource(SessionFactory sessionFactory) {
	Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
	if (getProperties != null) {
		Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
		if (props != null) {
			Object dataSourceValue = props.get(Environment.DATASOURCE);
			if (dataSourceValue instanceof DataSource) {
				return (DataSource) dataSourceValue;
			}
		}
	}
	if (sessionFactory instanceof SessionFactoryImplementor) {
		SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
		try {
			ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
			if (cp != null) {
				return cp.unwrap(DataSource.class);
			}
		}
		catch (UnknownServiceException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
			}
		}
	}
	return null;
}
 
Example 12
@Override
public ConnectionProvider initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	ConnectionProvider provider = ConnectionProviderInitiator.INSTANCE.initiateService(configurationValues, registry);
	if (provider instanceof DriverManagerConnectionProviderImpl) {
		registry.getService( SchemaManagementTool.class )
				.setCustomDatabaseGenerationTarget( new ReactiveGenerationTarget(registry) );
		return NoJdbcConnectionProvider.INSTANCE;
	}
	return provider;
}
 
Example 13
Source Project: java-technology-stack   Source File: SessionFactoryUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Determine the DataSource of the given SessionFactory.
 * @param sessionFactory the SessionFactory to check
 * @return the DataSource, or {@code null} if none found
 * @see ConnectionProvider
 */
@Nullable
public static DataSource getDataSource(SessionFactory sessionFactory) {
	Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
	if (getProperties != null) {
		Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
		if (props != null) {
			Object dataSourceValue = props.get(Environment.DATASOURCE);
			if (dataSourceValue instanceof DataSource) {
				return (DataSource) dataSourceValue;
			}
		}
	}
	if (sessionFactory instanceof SessionFactoryImplementor) {
		SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
		try {
			ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
			if (cp != null) {
				return cp.unwrap(DataSource.class);
			}
		}
		catch (UnknownServiceException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
			}
		}
	}
	return null;
}
 
Example 14
@Override
protected ConnectionProvider getAnyConnectionProvider() {
    String tenantId = tenantResolver().getDefaultTenantId();
    if (tenantId == null) {
        throw new IllegalStateException("Method 'TenantResolver.getDefaultTenantId()' returned a null value. "
                + "This violates the contract of the interface!");
    }
    return selectConnectionProvider(tenantId);
}
 
Example 15
@Override
protected ConnectionProvider selectConnectionProvider(final String tenantIdentifier) {
    LOG.debugv("selectConnectionProvider({0})", tenantIdentifier);

    ConnectionProvider provider = providerMap.get(tenantIdentifier);
    if (provider == null) {
        final ConnectionProvider connectionProvider = resolveConnectionProvider(tenantIdentifier);
        providerMap.put(tenantIdentifier, connectionProvider);
        return connectionProvider;
    }
    return provider;

}
 
Example 16
Source Project: quarkus   Source File: QuarkusConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isUnwrappableAs(final Class unwrapType) {
    return ConnectionProvider.class.equals(unwrapType) ||
            QuarkusConnectionProvider.class.isAssignableFrom(unwrapType) ||
            DataSource.class.isAssignableFrom(unwrapType) ||
            AgroalDataSource.class.isAssignableFrom(unwrapType);
}
 
Example 17
Source Project: quarkus   Source File: QuarkusConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T unwrap(final Class<T> unwrapType) {
    if (ConnectionProvider.class.equals(unwrapType) ||
            QuarkusConnectionProvider.class.isAssignableFrom(unwrapType)) {
        return (T) this;
    } else if (DataSource.class.isAssignableFrom(unwrapType) || AgroalDataSource.class.isAssignableFrom(unwrapType)) {
        return (T) dataSource;
    } else {
        throw new UnknownUnwrapTypeException(unwrapType);
    }
}
 
Example 18
public Connection getSqlConnection() {
	Connection connection = null;
	try {
		connection = getSessionFactory().
				getSessionFactoryOptions().getServiceRegistry().
				getService(ConnectionProvider.class).getConnection();
	} catch (SQLException e) {
		final InformationFrame INFORMATION_FRAME = new InformationFrame();
		INFORMATION_FRAME.setMessage("Connection converting error!\n" +e.getLocalizedMessage());
		INFORMATION_FRAME.setVisible(true);
	}
	return connection;
}
 
Example 19
Source Project: teiid-spring-boot   Source File: SchemaBuilderUtility.java    License: Apache License 2.0 5 votes vote down vote up
public static Metadata generateHbmModel(ConnectionProvider provider, Dialect dialect) throws SQLException {
    MetadataSources metadataSources = new MetadataSources();
    ServiceRegistry registry = metadataSources.getServiceRegistry();

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) registry).applySetting(AvailableSettings.DIALECT, TeiidDialect.class)
            .addService(ConnectionProvider.class, provider).addService(JdbcEnvironment.class,
                    new JdbcEnvironmentImpl(provider.getConnection().getMetaData(), dialect))
            .build();

    MetadataBuildingOptions options = new MetadataBuildingOptionsImpl(serviceRegistry);
    BootstrapContext bootstrapContext = new BootstrapContextImpl( serviceRegistry, options );

    ReverseEngineeringStrategy strategy = new DefaultReverseEngineeringStrategy();

    InFlightMetadataCollectorImpl metadataCollector =  new InFlightMetadataCollectorImpl(bootstrapContext, options);
    MetadataBuildingContext buildingContext = new MetadataBuildingContextRootImpl(bootstrapContext, options,
            metadataCollector);

    JDBCBinder binder = new JDBCBinder(serviceRegistry, new Properties(), buildingContext, strategy, false);
    Metadata metadata = metadataCollector.buildMetadataInstance(buildingContext);
    binder.readFromDatabase(null, null, buildMapping(metadata));
    HibernateMappingExporter exporter = new HibernateMappingExporter() {
        @Override
        public Metadata getMetadata() {
            return metadata;
        }
    };
    exporter.start();
    return metadata;
}
 
Example 20
public void prepare(boolean needsAutoCommit) throws SQLException {
	serviceRegistry = createServiceRegistry( cfgProperties );
	connection = serviceRegistry.getService( ConnectionProvider.class ).getConnection();
	if ( needsAutoCommit && ! connection.getAutoCommit() ) {
		connection.commit();
		connection.setAutoCommit( true );
	}
}
 
Example 21
@Override
@SuppressWarnings( {"unchecked"})
public <T> T unwrap(Class<T> unwrapType) {
	if ( ConnectionProvider.class.equals( unwrapType ) ||
			DriverManagerConnectionProviderImpl.class.isAssignableFrom( unwrapType ) ) {
		return (T) this;
	}
	else {
		throw new UnknownUnwrapTypeException( unwrapType );
	}
}
 
Example 22
@Override
@SuppressWarnings( {"unchecked"})
public <T> T unwrap(Class<T> unwrapType) {
	if ( ConnectionProvider.class.equals( unwrapType ) ||
			UserSuppliedConnectionProviderImpl.class.isAssignableFrom( unwrapType ) ) {
		return (T) this;
	}
	else {
		throw new UnknownUnwrapTypeException( unwrapType );
	}
}
 
Example 23
@Override
@SuppressWarnings( {"unchecked"})
public <T> T unwrap(Class<T> unwrapType) {
	if ( ConnectionProvider.class.equals( unwrapType ) ||
			DatasourceConnectionProviderImpl.class.isAssignableFrom( unwrapType ) ) {
		return (T) this;
	}
	else if ( DataSource.class.isAssignableFrom( unwrapType ) ) {
		return (T) getDataSource();
	}
	else {
		throw new UnknownUnwrapTypeException( unwrapType );
	}
}
 
Example 24
private Class<? extends ConnectionProvider> getSingleRegisteredProvider(StrategySelector strategySelector) {
	final Collection<Class<? extends ConnectionProvider>> implementors = strategySelector.getRegisteredStrategyImplementors( ConnectionProvider.class );
	if ( implementors != null && implementors.size() == 1 ) {
		return implementors.iterator().next();
	}

	return null;
}
 
Example 25
private ConnectionProvider instantiateExplicitConnectionProvider(Class providerClass) {
		try {
			return (ConnectionProvider) providerClass.newInstance();
		}
		catch (Exception e) {
			throw new HibernateException( "Could not instantiate connection provider [" + providerClass.getName() + "]", e );
		}
}
 
Example 26
private ConnectionProvider instantiateC3p0Provider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, C3P0_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.c3p0ProviderClassNotFound( C3P0_STRATEGY );
		return null;
	}
}
 
Example 27
private ConnectionProvider instantiateProxoolProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, PROXOOL_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.proxoolProviderClassNotFound( PROXOOL_STRATEGY );
		return null;
	}
}
 
Example 28
private ConnectionProvider instantiateHikariProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, HIKARI_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.hikariProviderClassNotFound();
		return null;
	}
}
 
Example 29
private ConnectionProvider instantiateViburProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, VIBUR_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.viburProviderClassNotFound();
		return null;
	}
}
 
Example 30
private ConnectionProvider instantiateAgroalProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, AGROAL_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.agroalProviderClassNotFound();
		return null;
	}
}