public SchemaExport(ServiceRegistry serviceRegistry, Configuration configuration) { this.connectionHelper = new SuppliedConnectionProviderConnectionHelper( serviceRegistry.getService( ConnectionProvider.class ) ); this.sqlStatementLogger = serviceRegistry.getService( JdbcServices.class ).getSqlStatementLogger(); this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); this.sqlExceptionHelper = serviceRegistry.getService( JdbcServices.class ).getSqlExceptionHelper(); this.importFiles = ConfigurationHelper.getString( AvailableSettings.HBM2DDL_IMPORT_FILES, configuration.getProperties(), DEFAULT_IMPORT_FILE ); final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect(); this.dropSQL = configuration.generateDropSchemaScript( dialect ); this.createSQL = configuration.generateSchemaCreationScript( dialect ); }
public SchemaExport(MetadataImplementor metadata) { ServiceRegistry serviceRegistry = metadata.getServiceRegistry(); this.connectionHelper = new SuppliedConnectionProviderConnectionHelper( serviceRegistry.getService( ConnectionProvider.class ) ); JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); this.sqlStatementLogger = jdbcServices.getSqlStatementLogger(); this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper(); this.importFiles = ConfigurationHelper.getString( AvailableSettings.HBM2DDL_IMPORT_FILES, serviceRegistry.getService( ConfigurationService.class ).getSettings(), DEFAULT_IMPORT_FILE ); final Dialect dialect = jdbcServices.getDialect(); this.dropSQL = metadata.getDatabase().generateDropSchemaScript( dialect ); this.createSQL = metadata.getDatabase().generateSchemaCreationScript( dialect ); }
@Override public JdbcConnectionAccess getJdbcConnectionAccess() { if ( jdbcConnectionAccess == null ) { if ( MultiTenancyStrategy.NONE == factory.getSettings().getMultiTenancyStrategy() ) { jdbcConnectionAccess = new NonContextualJdbcConnectionAccess( getEventListenerManager(), factory.getServiceRegistry().getService( ConnectionProvider.class ) ); } else { jdbcConnectionAccess = new ContextualJdbcConnectionAccess( getEventListenerManager(), factory.getServiceRegistry().getService( MultiTenantConnectionProvider.class ) ); } } return jdbcConnectionAccess; }
private JdbcConnectionAccess buildLocalConnectionAccess() { return new JdbcConnectionAccess() { @Override public Connection obtainConnection() throws SQLException { return settings.getMultiTenancyStrategy() == MultiTenancyStrategy.NONE ? serviceRegistry.getService( ConnectionProvider.class ).getConnection() : serviceRegistry.getService( MultiTenantConnectionProvider.class ).getAnyConnection(); } @Override public void releaseConnection(Connection connection) throws SQLException { if ( settings.getMultiTenancyStrategy() == MultiTenancyStrategy.NONE ) { serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection ); } else { serviceRegistry.getService( MultiTenantConnectionProvider.class ).releaseAnyConnection( connection ); } } @Override public boolean supportsAggressiveRelease() { return false; } }; }
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 */ 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 SessionFactory build(final RemoteCredentialHibernateBundle<?> bundle, final Environment environment, final PooledDataSourceFactory dbConfig, final ManagedDataSource dataSource, final List<Class<?>> entities) { final ConnectionProvider provider = this.buildConnectionProvider(dataSource, dbConfig.getProperties()); final SessionFactory factory = this.buildSessionFactory(bundle, dbConfig, provider, dbConfig.getProperties(), entities); final SessionFactoryManager managedFactory = new SessionFactoryManager(factory, dataSource); environment.lifecycle().manage(managedFactory); return factory; }
private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration(); Properties props = new Properties(); props.put("hibernate.current_session_context_class", "thread"); configuration.setProperties(props); for (Class<?> clazz : entityClasses) { configuration.addAnnotatedClass(clazz); } PluginHandler.get().getPlugin().addAnnotatedClass(configuration); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()) .addService(ConnectionProvider.class, new NomadConnectionProvider()).build(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { logger.error("Failed to build session factory.", ex); throw new ExceptionInInitializerError(ex); } }
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; } }
@Test public void testSelectStatementWithStatementsCache() throws SQLException { Session session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession(); ConnectionProvider cp = ((SessionFactoryImplementor) session.getSessionFactory()) .getServiceRegistry().getService(ConnectionProvider.class); ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource(); ConcurrentMap<StatementMethod, StatementHolder> mockedStatementCache = mockStatementCache(ds); executeAndVerifySelectInSession(session); // resources/hibernate-with-stmt-cache.cfg.xml defines pool with 1 connection only, that's why // the second session will get and use the same underlying connection. session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession(); executeAndVerifySelectInSession(session); 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()); }
/** * Builds a {@link SessionFactory} * @param bundle * the bundle * @param dbConfig * the dbconfig * @param connectionProvider * the connection provider * @param properties * the hibernate properties * @param entities * the persistent entities * @return {@link SessionFactory} */ private SessionFactory buildSessionFactory(RoutingHibernateBundle<?> bundle, DataSourceFactory dbConfig, ConnectionProvider connectionProvider, Map<String, String> properties, List<Class<?>> entities) { final Configuration configuration = new Configuration(); configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed"); configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS, Boolean.toString(dbConfig.isAutoCommentsEnabled())); configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true"); configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true"); configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true"); configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true"); configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true"); configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true"); for (Map.Entry<String, String> property : properties.entrySet()) { configuration.setProperty(property.getKey(), property.getValue()); } addAnnotatedClasses(configuration, entities); bundle.configure(configuration); final ServiceRegistry registry = new StandardServiceRegistryBuilder() .addService(ConnectionProvider.class, connectionProvider).applySettings(properties).build(); return configuration.buildSessionFactory(registry); }
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 void prepare(boolean needsAutoCommit) throws SQLException { serviceRegistry = createServiceRegistry( cfgProperties ); connection = serviceRegistry.getService( ConnectionProvider.class ).getConnection(); if ( needsAutoCommit && ! connection.getAutoCommit() ) { connection.commit(); connection.setAutoCommit( true ); } }
private void releaseConnection() throws SQLException { if ( connection != null ) { try { new SqlExceptionHelper().logAndClearWarnings( connection ); } finally { try { serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection ); } finally { connection = null; } } } }
@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 ConnectionProvider instantiateExplicitConnectionProvider( String providerName, StrategySelector strategySelector) { try { LOG.instantiatingExplicitConnectionProvider( providerName ); // This relies on selectStrategyImplementor trying // classLoaderService.classForName( name ). // TODO: Maybe we shouldn't rely on that here and do it manually? return strategySelector.selectStrategyImplementor( ConnectionProvider.class, providerName ).newInstance(); } catch ( Exception e ) { throw new HibernateException( "Could not instantiate connection provider [" + providerName + "]", 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 JdbcConnectionAccess buildJdbcConnectionAccess(Map configValues) { final MultiTenancyStrategy multiTenancyStrategy = MultiTenancyStrategy.determineMultiTenancyStrategy( configValues ); if ( MultiTenancyStrategy.NONE == multiTenancyStrategy ) { connectionProvider = serviceRegistry.getService( ConnectionProvider.class ); return new ConnectionProviderJdbcConnectionAccess( connectionProvider ); } else { connectionProvider = null; final MultiTenantConnectionProvider multiTenantConnectionProvider = serviceRegistry.getService( MultiTenantConnectionProvider.class ); return new MultiTenantConnectionProviderJdbcConnectionAccess( multiTenantConnectionProvider ); } }
@Override @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> unwrapType) { if (ConnectionProvider.class.equals(unwrapType) || DBCPConnectionProvider.class.isAssignableFrom(unwrapType)) { return (T) this; } if (DataSource.class.isAssignableFrom(unwrapType)) { return (T) this.dataSource; } throw new UnknownUnwrapTypeException(unwrapType); }
private ConnectionProvider buildConnectionProvider(final DataSource dataSource, final Map<String, String> properties) { final DatasourceConnectionProviderImpl connectionProvider = new DatasourceConnectionProviderImpl(); connectionProvider.setDataSource(dataSource); connectionProvider.configure(properties); return connectionProvider; }
private SessionFactory buildSessionFactory(final RemoteCredentialHibernateBundle<?> bundle, final PooledDataSourceFactory dbConfig, final ConnectionProvider connectionProvider, final Map<String, String> properties, final List<Class<?>> entities) { final Configuration configuration = new Configuration(); configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed"); configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS, Boolean.toString(dbConfig.isAutoCommentsEnabled())); configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true"); configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true"); configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true"); configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true"); configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true"); configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true"); for (final Map.Entry<String, String> property : properties.entrySet()) { configuration.setProperty(property.getKey(), property.getValue()); } this.addAnnotatedClasses(configuration, entities); final ServiceRegistry registry = new StandardServiceRegistryBuilder() .addService(ConnectionProvider.class, connectionProvider) .applySettings(properties) .build(); this.configure(configuration, registry); return configuration.buildSessionFactory(registry); }
@Override @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> unwrapType) { if ( ConnectionProvider.class.equals( unwrapType ) || HikariConnectionProvider.class.isAssignableFrom( unwrapType ) ) { return (T) this; } else if ( DataSource.class.isAssignableFrom( unwrapType ) ) { return (T) this.hds; } else { throw new UnknownUnwrapTypeException( unwrapType ); } }
@Override @SuppressWarnings({ "unchecked" }) public <T> T unwrap(final Class<T> unwrapType) { if (ConnectionProvider.class.equals(unwrapType) || BeanLookupDatasourceConnectionProvider.class.isAssignableFrom(unwrapType)) { return (T) this; } else if (DataSource.class.isAssignableFrom(unwrapType)) { return (T) dataSource; } else { throw new UnknownUnwrapTypeException(unwrapType); } }
/** * Extrait une DataSource d'une EntityManagerFactory */ public static DataSource applicationDataSource(EntityManagerFactory entityManagerFactory) { EntityManagerImpl entityManagerImpl = (EntityManagerImpl) entityManagerFactory.createEntityManager(); try { HikariCPConnectionProvider hikariCPConnectionProvider = (HikariCPConnectionProvider) entityManagerImpl.getFactory().getSessionFactory().getServiceRegistry().getService(ConnectionProvider.class); Field dataSourceField = HikariCPConnectionProvider.class.getDeclaredField("hds"); dataSourceField.setAccessible(true); return (HikariDataSource) dataSourceField.get(hikariCPConnectionProvider); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } finally { entityManagerImpl.close(); } }
public Connection getConnection() { Connection connection = null; try { Session session = (Session) em.getDelegate(); SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory(); ConnectionProvider cp = sfi.getConnectionProvider(); connection = (Connection) cp.getConnection(); return connection; } catch (Exception ex) { ex.printStackTrace(); } return connection; }
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(); } }
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(); } }
@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) this.dataSource; } else { throw new UnknownUnwrapTypeException(unwrapType); } }
@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" ); }
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; }
public static Connection getConnection(ServiceRegistry serviceRegistry) { try { return serviceRegistry.getService(ConnectionProvider.class).getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } }
@Override protected void configure() { // bind the ConnectionProvider bind(ConnectionProvider.class).to(TomcatJDBCConnectionProvider.class); bind(PersistService.class).to(CroquetPersistService.class); bind(UnitOfWork.class).to(CroquetPersistService.class); bind(EntityManager.class).toProvider(CroquetPersistService.class); bind(EntityManagerFactory.class).toProvider(CroquetPersistService.EntityManagerFactoryProvider.class); }
/** * Constructs the {@link CroquetPersistService}. * @param settings the settings to configure everything with. * @param connectionProvider the {@link ConnectionProvider} to use. */ @Inject public CroquetPersistService(final AbstractSettings settings, @Nullable @Named("jpa-unit-name") final String persistenceUnitName, final ConnectionProvider connectionProvider) { this.settings = settings; this.persistenceUnitName = persistenceUnitName; this.connectionProvider = connectionProvider; }
public ConnectionProvider getConnectionProvider() { return sessionFactoryImplementor.getConnectionProvider(); }