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

The following examples show how to use org.hibernate.engine.jdbc.connections.spi.ConnectionProvider. 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
Source File: SessionFactoryImpl.java    From lams with 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 #2
Source File: AbstractSharedSessionContract.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #3
Source File: BaseReactiveTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #4
Source File: ManagedProviderConnectionHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #5
Source File: DataSourceTenantConnectionResolver.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: SessionFactoryUtils.java    From spring4-understanding with 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 #7
Source File: SessionFactoryUtils.java    From lams with 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 #8
Source File: HibernateMultiTenantConnectionProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: HibernateUtil.java    From unitime with 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 #10
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with 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 #11
Source File: ConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ConnectionProvider instantiateHikariProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, HIKARI_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.hikariProviderClassNotFound();
		return null;
	}
}
 
Example #12
Source File: SessionFactoryUtils.java    From spring-analysis-note with 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 #13
Source File: ConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ConnectionProvider instantiateAgroalProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, AGROAL_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.agroalProviderClassNotFound();
		return null;
	}
}
 
Example #14
Source File: ConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ConnectionProvider instantiateViburProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, VIBUR_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.viburProviderClassNotFound();
		return null;
	}
}
 
Example #15
Source File: DataSourceFactory.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 5 votes vote down vote up
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 #16
Source File: ConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ConnectionProvider instantiateProxoolProvider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, PROXOOL_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.proxoolProviderClassNotFound( PROXOOL_STRATEGY );
		return null;
	}
}
 
Example #17
Source File: ConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ConnectionProvider instantiateC3p0Provider(StrategySelector strategySelector) {
	try {
		return strategySelector.selectStrategyImplementor( ConnectionProvider.class, C3P0_STRATEGY ).newInstance();
	}
	catch ( Exception e ) {
		LOG.c3p0ProviderClassNotFound( C3P0_STRATEGY );
		return null;
	}
}
 
Example #18
Source File: SchemaBuilderUtility.java    From teiid-spring-boot with 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 #19
Source File: QuarkusConnectionProvider.java    From quarkus with 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 #20
Source File: JdbcEnvironmentInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private JdbcConnectionAccess buildJdbcConnectionAccess(Map configValues, ServiceRegistryImplementor registry) {
	final MultiTenancyStrategy multiTenancyStrategy = MultiTenancyStrategy.determineMultiTenancyStrategy(
			configValues
	);
	if ( !multiTenancyStrategy.requiresMultiTenantConnectionProvider() ) {
		ConnectionProvider connectionProvider = registry.getService( ConnectionProvider.class );
		return new ConnectionProviderJdbcConnectionAccess( connectionProvider );
	}
	else {
		final MultiTenantConnectionProvider multiTenantConnectionProvider = registry.getService( MultiTenantConnectionProvider.class );
		return new MultiTenantConnectionProviderJdbcConnectionAccess( multiTenantConnectionProvider );
	}
}
 
Example #21
Source File: JdbcEnvironmentInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static JdbcConnectionAccess buildBootstrapJdbcConnectionAccess(
		MultiTenancyStrategy multiTenancyStrategy,
		ServiceRegistryImplementor registry) {
	if ( !multiTenancyStrategy.requiresMultiTenantConnectionProvider() ) {
		ConnectionProvider connectionProvider = registry.getService( ConnectionProvider.class );
		return new ConnectionProviderJdbcConnectionAccess( connectionProvider );
	}
	else {
		final MultiTenantConnectionProvider multiTenantConnectionProvider = registry.getService( MultiTenantConnectionProvider.class );
		return new MultiTenantConnectionProviderJdbcConnectionAccess( multiTenantConnectionProvider );
	}
}
 
Example #22
Source File: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public static Connection getConnection() throws SQLException {
  return sessionFactory
      .getSessionFactoryOptions()
      .getServiceRegistry()
      .getService(ConnectionProvider.class)
      .getConnection();
}
 
Example #23
Source File: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static void createTablesLiquibaseMigration(MetadataSources metaDataSrc)
    throws LiquibaseException, SQLException, InterruptedException {
  // Get database connection
  try (Connection con =
      metaDataSrc.getServiceRegistry().getService(ConnectionProvider.class).getConnection()) {
    JdbcConnection jdbcCon = new JdbcConnection(con);

    // Overwrite default liquibase table names by custom
    GlobalConfiguration liquibaseConfiguration =
        LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class);
    liquibaseConfiguration.setDatabaseChangeLogLockWaitTime(1L);

    // Initialize Liquibase and run the update
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(jdbcCon);
    String rootPath = System.getProperty(ModelDBConstants.userDir);
    rootPath = rootPath + "\\src\\main\\resources\\liquibase\\db-changelog-1.0.xml";
    Liquibase liquibase = new Liquibase(rootPath, new FileSystemResourceAccessor(), database);

    boolean liquibaseExecuted = false;
    while (!liquibaseExecuted) {
      try {
        liquibase.update(new Contexts(), new LabelExpression());
        liquibaseExecuted = true;
      } catch (LockException ex) {
        LOGGER.warn(
            "ModelDBHibernateUtil createTablesLiquibaseMigration() getting LockException ", ex);
        releaseLiquibaseLock(metaDataSrc);
      }
    }
  }
}
 
Example #24
Source File: YPersistenceManager.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void closeFactory() {                    // shutdown persistence engine
    if (factory != null) {
        if (factory instanceof SessionFactoryImpl) {
           SessionFactoryImpl sf = (SessionFactoryImpl) factory;
           ConnectionProvider conn = sf.getConnectionProvider();
           if (conn instanceof C3P0ConnectionProvider) {
             ((C3P0ConnectionProvider)conn).stop();
           }
        }

        factory.close();
    }
}
 
Example #25
Source File: HibernateEngine.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void closeFactory() {
    if (_factory != null) {
        if (_factory instanceof SessionFactoryImpl) {
           SessionFactoryImpl sf = (SessionFactoryImpl) _factory;
           ConnectionProvider conn = sf.getConnectionProvider();
           if (conn instanceof C3P0ConnectionProvider) {
             ((C3P0ConnectionProvider)conn).stop();
           }
        }

        _factory.close();
    }
}
 
Example #26
Source File: SimpleMultiTenantConnectionProvider.java    From HibernateDemos with The Unlicense 5 votes vote down vote up
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
	if ( TENANT_ID_1.equals( tenantIdentifier ) ) {
		return foo1ConnectionProvider;
	}
	else if ( TENANT_ID_2.equals( tenantIdentifier ) ) {
		return foo2ConnectionProvider;
	}
	throw new IllegalArgumentException( "Unknown tenant identifier" );
}
 
Example #27
Source File: SimpleMultiTenantConnectionProvider.java    From HibernateDemos with The Unlicense 5 votes vote down vote up
private ConnectionProvider buildConnectionProvider(String dbName) {
	Properties props = new Properties( null );
	props.put( "hibernate.connection.driver_class", DRIVER );
	// Inject dbName into connection url string.
	props.put( "hibernate.connection.url", String.format( URL, dbName ) );
	props.put( "hibernate.connection.username", USER );
	props.put( "hibernate.connection.password", PASS );
	
	// Note that DriverManagerConnectionProviderImpl is an internal class.  However, rather than creating
	// a ConnectionProvider, I'm using it for simplicity's sake.
	// DriverManagerConnectionProviderImpl obtains a Connection through the JDBC Driver#connect
	DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
	connectionProvider.configure( props );
	return connectionProvider;
}
 
Example #28
Source File: SimpleMultiTenantConnectionProvider.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
	if ( TENANT_ID_1.equals( tenantIdentifier ) ) {
		return foo1ConnectionProvider;
	}
	else if ( TENANT_ID_2.equals( tenantIdentifier ) ) {
		return foo2ConnectionProvider;
	}
	throw new IllegalArgumentException( "Unknown tenant identifier" );
}
 
Example #29
Source File: SimpleMultiTenantConnectionProvider.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
private ConnectionProvider buildConnectionProvider(String dbName) {
	Properties props = new Properties( null );
	props.put( "hibernate.connection.driver_class", DRIVER );
	// Inject dbName into connection url string.
	props.put( "hibernate.connection.url", String.format( URL, dbName ) );
	props.put( "hibernate.connection.username", USER );
	props.put( "hibernate.connection.password", PASS );
	
	// Note that DriverManagerConnectionProviderImpl is an internal class.  However, rather than creating
	// a ConnectionProvider, I'm using it for simplicity's sake.
	// DriverManagerConnectionProviderImpl obtains a Connection through the JDBC Driver#connect
	DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
	connectionProvider.configure( props );
	return connectionProvider;
}
 
Example #30
Source File: SchemaMultiTenantConnectionProvider.java    From tutorials with MIT License 5 votes vote down vote up
private ConnectionProvider initConnectionProvider() throws IOException {
    Properties properties = new Properties();
    properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));

    DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
    connectionProvider.configure(properties);
    return connectionProvider;
}