下面列出了怎么用org.hibernate.engine.jdbc.connections.spi.ConnectionProvider的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
} );
}
@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);
}
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;
}
/**
* 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;
}
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;
}
}
}
}
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;
}
};
}
@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;
}
/**
* 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;
}
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;
}
}
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;
}
}
/**
* 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;
}
@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;
}
/**
* 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;
}
@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);
}
@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;
}
@Override
public boolean isUnwrappableAs(final Class unwrapType) {
return ConnectionProvider.class.equals(unwrapType) ||
QuarkusConnectionProvider.class.isAssignableFrom(unwrapType) ||
DataSource.class.isAssignableFrom(unwrapType) ||
AgroalDataSource.class.isAssignableFrom(unwrapType);
}
@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);
}
}
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;
}
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;
}
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 );
}
}
@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 );
}
}
@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 );
}
}
@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 );
}
}
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;
}
private ConnectionProvider instantiateExplicitConnectionProvider(Class providerClass) {
try {
return (ConnectionProvider) providerClass.newInstance();
}
catch (Exception e) {
throw new HibernateException( "Could not instantiate connection provider [" + providerClass.getName() + "]", e );
}
}
private ConnectionProvider instantiateC3p0Provider(StrategySelector strategySelector) {
try {
return strategySelector.selectStrategyImplementor( ConnectionProvider.class, C3P0_STRATEGY ).newInstance();
}
catch ( Exception e ) {
LOG.c3p0ProviderClassNotFound( C3P0_STRATEGY );
return null;
}
}
private ConnectionProvider instantiateProxoolProvider(StrategySelector strategySelector) {
try {
return strategySelector.selectStrategyImplementor( ConnectionProvider.class, PROXOOL_STRATEGY ).newInstance();
}
catch ( Exception e ) {
LOG.proxoolProviderClassNotFound( PROXOOL_STRATEGY );
return null;
}
}
private ConnectionProvider instantiateHikariProvider(StrategySelector strategySelector) {
try {
return strategySelector.selectStrategyImplementor( ConnectionProvider.class, HIKARI_STRATEGY ).newInstance();
}
catch ( Exception e ) {
LOG.hikariProviderClassNotFound();
return null;
}
}
private ConnectionProvider instantiateViburProvider(StrategySelector strategySelector) {
try {
return strategySelector.selectStrategyImplementor( ConnectionProvider.class, VIBUR_STRATEGY ).newInstance();
}
catch ( Exception e ) {
LOG.viburProviderClassNotFound();
return null;
}
}
private ConnectionProvider instantiateAgroalProvider(StrategySelector strategySelector) {
try {
return strategySelector.selectStrategyImplementor( ConnectionProvider.class, AGROAL_STRATEGY ).newInstance();
}
catch ( Exception e ) {
LOG.agroalProviderClassNotFound();
return null;
}
}