List of usage examples for org.hibernate.internal SessionFactoryImpl getServiceRegistry
@Override
public ServiceRegistryImplementor getServiceRegistry()
From source file:at.molindo.esi4j.module.hibernate.DefaultHibernateLifecycleInjector.java
License:Apache License
@Override public synchronized void injectLifecycle(SessionFactory sessionFactory, Esi4JBatchedEventProcessor batchedEventProcessor) { if (_listener != null) { throw new IllegalStateException("already injected"); }//from w w w. j av a 2s .co m SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory; EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry() .getService(EventListenerRegistry.class); _listener = doCreateListener(sessionFactoryImpl, batchedEventProcessor); if (_listener instanceof PostInsertEventListener) { if (registerPostCommitListeneres) { registry.appendListeners(EventType.POST_COMMIT_INSERT, (PostInsertEventListener) _listener); } else { registry.appendListeners(EventType.POST_INSERT, (PostInsertEventListener) _listener); } } if (_listener instanceof PostUpdateEventListener) { if (registerPostCommitListeneres) { registry.appendListeners(EventType.POST_COMMIT_UPDATE, (PostUpdateEventListener) _listener); } else { registry.appendListeners(EventType.POST_UPDATE, (PostUpdateEventListener) _listener); } } if (_listener instanceof PostDeleteEventListener) { if (registerPostCommitListeneres) { registry.appendListeners(EventType.POST_COMMIT_DELETE, (PostDeleteEventListener) _listener); } else { registry.appendListeners(EventType.POST_DELETE, (PostDeleteEventListener) _listener); } } // collections if (!registerPostCommitListeneres) { if (_listener instanceof PostCollectionRecreateEventListener) { registry.appendListeners(EventType.POST_COLLECTION_RECREATE, (PostCollectionRecreateEventListener) _listener); } if (_listener instanceof PostCollectionRemoveEventListener) { registry.appendListeners(EventType.POST_COLLECTION_REMOVE, (PostCollectionRemoveEventListener) _listener); } if (_listener instanceof PostCollectionUpdateEventListener) { registry.appendListeners(EventType.POST_COLLECTION_UPDATE, (PostCollectionUpdateEventListener) _listener); } } }
From source file:at.molindo.esi4j.module.hibernate.DefaultHibernateLifecycleInjector.java
License:Apache License
@Override public synchronized void removeLifecycle(SessionFactory sessionFactory) { if (_listener == null) { return;/* ww w . ja v a 2 s . c om*/ } SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory; EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry() .getService(EventListenerRegistry.class); if (registerPostCommitListeneres) { removeListeners(registry, _listener, POST_COMMIT_INSERT, POST_COMMIT_UPDATE, POST_COMMIT_DELETE); } else { removeListeners(registry, _listener, POST_INSERT, POST_UPDATE, POST_DELETE, POST_COLLECTION_RECREATE, POST_COLLECTION_UPDATE, POST_COLLECTION_REMOVE); } _listener = null; }
From source file:com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.java
License:Apache License
private boolean autoUpdateClosureTableStructure() { if (baseHelper.getConfiguration().isSkipOrgClosureStructureCheck()) { LOGGER.debug("Skipping org closure structure check."); return false; }/* w w w .j a va2 s . c o m*/ SessionFactory sf = baseHelper.getSessionFactory(); if (sf instanceof SessionFactoryImpl) { SessionFactoryImpl sfi = ((SessionFactoryImpl) sf); LOGGER.debug("SessionFactoryImpl.getSettings() = {}; auto update schema = {}", sfi.getSettings(), sfi.getSettings() != null ? sfi.getSettings().isAutoUpdateSchema() : null); if (sfi.getSettings() != null && sfi.getSettings().isAutoUpdateSchema()) { LOGGER.info("Checking the closure table structure."); final Session session = baseHelper.getSessionFactory().openSession(); final Holder<Boolean> wrongNumberOfColumns = new Holder<>(false); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { DatabaseMetaData meta = connection.getMetaData(); if (meta == null) { LOGGER.warn("No database metadata found."); } else { ResultSet rsColumns = meta.getColumns(null, null, CLOSURE_TABLE_NAME, null); int columns = 0; while (rsColumns.next()) { LOGGER.debug("Column: {} {}", rsColumns.getString("TYPE_NAME"), rsColumns.getString("COLUMN_NAME")); columns++; } if (columns > 0) { LOGGER.debug("There are {} columns in {} (obtained via DatabaseMetaData)", columns, CLOSURE_TABLE_NAME); if (columns != 3) { wrongNumberOfColumns.setValue(true); } return; } // perhaps some problem here... let's try another way out try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from " + CLOSURE_TABLE_NAME); int cols = rs.getMetaData().getColumnCount(); if (cols > 0) { LOGGER.debug( "There are {} columns in {} (obtained via resultSet.getMetaData())", cols, CLOSURE_TABLE_NAME); if (cols != 3) { wrongNumberOfColumns.setValue(true); } } else { LOGGER.warn( "Couldn't determine the number of columns in {}. In case of problems, please fix your database structure manually using DB scripts in 'config' folder.", CLOSURE_TABLE_NAME); } rs.close(); // don't care about closing them in case of failure stmt.close(); } catch (RuntimeException e) { LoggingUtils.logException(LOGGER, "Couldn't obtain the number of columns in {}. In case of problems running midPoint, please fix your database structure manually using DB scripts in 'config' folder.", e, CLOSURE_TABLE_NAME); } } } }); if (wrongNumberOfColumns.getValue()) { session.getTransaction().begin(); LOGGER.info("Wrong number of columns detected; dropping table " + CLOSURE_TABLE_NAME); Query q = session.createSQLQuery("drop table " + CLOSURE_TABLE_NAME); q.executeUpdate(); session.getTransaction().commit(); LOGGER.info( "Calling hibernate hbm2ddl SchemaUpdate tool to create the table in the necessary form."); new SchemaUpdate(sfi.getServiceRegistry(), baseHelper.getSessionFactoryBean().getConfiguration()).execute(false, true); LOGGER.info( "Done, table was (hopefully) created. If not, please fix your database structure manually using DB scripts in 'config' folder."); return true; } } else { // auto schema update is disabled } } else { LOGGER.warn("SessionFactory is not of type SessionFactoryImpl; it is {}", sf != null ? sf.getClass() : "null"); } return false; }
From source file:fredboat.db.DatabaseManager.java
License:Open Source License
/** * Starts the database connection.// www. j a v a 2 s . c o m * * @throws IllegalStateException if trying to start a database that is READY or INITIALIZING */ public synchronized void startup() { if (state == DatabaseState.READY || state == DatabaseState.INITIALIZING) { throw new IllegalStateException("Can't start the database, when it's current state is " + state); } state = DatabaseState.INITIALIZING; try { if (Config.CONFIG.isUseSshTunnel()) { //don't connect again if it's already connected if (sshTunnel == null || !sshTunnel.isConnected()) { connectSSH(); } } //These are now located in the resources directory as XML Properties properties = new Properties(); properties.put("configLocation", "hibernate.cfg.xml"); properties.put("hibernate.connection.provider_class", "org.hibernate.hikaricp.internal.HikariCPConnectionProvider"); properties.put("hibernate.connection.url", jdbcUrl); if (dialect != null && !"".equals(dialect)) properties.put("hibernate.dialect", dialect); properties.put("hibernate.cache.use_second_level_cache", "true"); properties.put("hibernate.cache.provider_configuration_file_resource_path", "ehcache.xml"); properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory"); //this does a lot of logs //properties.put("hibernate.show_sql", "true"); //automatically update the tables we need //caution: only add new columns, don't remove or alter old ones, otherwise manual db table migration needed properties.put("hibernate.hbm2ddl.auto", "update"); //disable autocommit, it is not recommended for our usecases, and interferes with some of them // see https://vladmihalcea.com/2017/05/17/why-you-should-always-use-hibernate-connection-provider_disables_autocommit-for-resource-local-jpa-transactions/ // this also means all EntityManager interactions need to be wrapped into em.getTransaction.begin() and // em.getTransaction.commit() to prevent a rollback spam at the database properties.put("hibernate.connection.autocommit", "true"); properties.put("hibernate.connection.provider_disables_autocommit", "false"); properties.put("hibernate.hikari.maximumPoolSize", Integer.toString(poolSize)); //how long to wait for a connection becoming available, also the timeout when a DB fails properties.put("hibernate.hikari.connectionTimeout", Integer.toString(Config.HIKARI_TIMEOUT_MILLISECONDS)); //this helps with sorting out connections in pgAdmin properties.put("hibernate.hikari.dataSource.ApplicationName", "FredBoat_" + Config.CONFIG.getDistribution()); //timeout the validation query (will be done automatically through Connection.isValid()) properties.put("hibernate.hikari.validationTimeout", "1000"); properties.put("hibernate.hikari.driverClassName", driverClassName); LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean(); emfb.setPackagesToScan("fredboat.db.entity"); emfb.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); emfb.setJpaProperties(properties); emfb.setPersistenceUnitName(DEFAULT_PERSISTENCE_UNIT_NAME); emfb.setPersistenceProviderClass(HibernatePersistenceProvider.class); emfb.afterPropertiesSet(); //leak prevention, close existing factory if possible closeEntityManagerFactory(); emf = emfb.getObject(); try { //add metrics to hikari and hibernate SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class); sessionFactory.getServiceRegistry().getService(ConnectionProvider.class) .unwrap(HikariDataSource.class).setMetricsTrackerFactory(Metrics.instance().hikariStats); //NOTE the register() on the HibernateCollector may only be called once so this will break in case we create 2 connections Metrics.instance().hibernateStats.add(sessionFactory, DEFAULT_PERSISTENCE_UNIT_NAME).register(); } catch (Exception e) { log.warn( "Exception when registering database metrics. This is not expected to happen outside of tests.", e); } //adjusting the ehcache config if (!Config.CONFIG.isUseSshTunnel()) { //local database: turn off overflow to disk of the cache for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) { for (String cacheName : cacheManager.getCacheNames()) { CacheConfiguration cacheConfig = cacheManager.getCache(cacheName).getCacheConfiguration(); cacheConfig.getPersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE); } } } for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) { log.debug(cacheManager.getActiveConfigurationText()); } log.info("Started Hibernate"); state = DatabaseState.READY; } catch (Exception ex) { state = DatabaseState.FAILED; throw new RuntimeException("Failed starting database connection", ex); } }
From source file:net.sf.beanlib.hibernate4.Hibernate4SequenceGenerator.java
License:Apache License
/** Returns the identifier generator created for the specified sequence and session. */ private static IdentifierGenerator createIdentifierGenerator(String sequenceName, Session session) { SessionFactory sessionFactory = session.getSessionFactory(); if (!(sessionFactory instanceof SessionFactoryImpl)) { throw new IllegalStateException("Not yet know how to handle the session factory of the given session!"); }//from w w w. ja va 2 s . c om SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory; // Dialect dialect = sessionFactoryImpl.getDialect(); ServiceRegistry registry = sessionFactoryImpl.getServiceRegistry(); Properties params = new Properties(); params.setProperty("sequence", sequenceName); SequenceStyleGenerator sequenceStyleGenerator = new SequenceStyleGenerator(); sequenceStyleGenerator.configure(LongType.INSTANCE, params, (ServiceRegistry) registry); // SequenceGenerator sequenceGenerator = new SequenceGenerator(); // sequenceGenerator.configure(LongType.INSTANCE, params, dialect); return sequenceStyleGenerator; }
From source file:org.babyfish.hibernate.cfg.Configuration.java
License:Open Source License
@Override public XSessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throws HibernateException { Arguments.mustBeInstanceOfValue("serviceRegistry", Arguments.mustNotBeNull("serviceRegistry", serviceRegistry), StandardServiceRegistryImpl.class); replacePersisterClassResolver((AbstractServiceRegistryImpl) serviceRegistry); String originalCurrentSessionContext = this.getProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS); this.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); SessionFactoryImpl factory; try {/*w ww .jav a 2s. c om*/ pathPlanKeyVlidationSuspended = true; try { factory = (SessionFactoryImpl) super.buildSessionFactory(serviceRegistry); } finally { pathPlanKeyVlidationSuspended = false; } } finally { if (originalCurrentSessionContext != null) { this.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, originalCurrentSessionContext); } else { this.getProperties().remove(Environment.CURRENT_SESSION_CONTEXT_CLASS); } } if (originalCurrentSessionContext != null) { factory.getProperties().setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, originalCurrentSessionContext); } else { factory.getProperties().remove(Environment.CURRENT_SESSION_CONTEXT_CLASS); } Dialect dialect = factory.getDialect(); if (dialect instanceof InstallableDialect) { ((InstallableDialect) dialect).install(factory); } EventListenerGroup<MergeEventListener> mergeEventListenerGroup = factory.getServiceRegistry() .getService(EventListenerRegistry.class).getEventListenerGroup(EventType.MERGE); MergeEventListener mergeEventListener = new ObjectModelMergeEventListener( mergeEventListenerGroup.listeners()); mergeEventListenerGroup.clear(); mergeEventListenerGroup.appendListener(mergeEventListener); setQueryPlanceCache(factory, this.createQueryPlanCache(factory)); for (ClassMetadata classMetadata : factory.getAllClassMetadata().values()) { if (Metadatas.getObjectModelFactoryProvider(classMetadata.getMappedClass()) != null) { //Validate whether JPA configuration is same with object model configuration HibernateMetadatas.of(classMetadata.getMappedClass()).getPersistentClass(factory); } } return SessionFactoryImplWrapper.wrap(factory); }
From source file:org.candlepin.guice.CandlepinContextListener.java
License:Open Source License
/** * There's no way to really get Guice to perform injections on stuff that * the JpaPersistModule is creating, so we resort to grabbing the EntityManagerFactory * after the fact and adding the Validation EventListener ourselves. * @param injector/* w w w . j av a 2s . co m*/ */ private void insertValidationEventListeners(Injector injector) { javax.inject.Provider<EntityManagerFactory> emfProvider = injector.getProvider(EntityManagerFactory.class); HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) emfProvider .get(); SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory .getSessionFactory(); EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry() .getService(EventListenerRegistry.class); javax.inject.Provider<BeanValidationEventListener> listenerProvider = injector .getProvider(BeanValidationEventListener.class); registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(listenerProvider.get()); registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(listenerProvider.get()); registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(listenerProvider.get()); }
From source file:org.candlepin.gutterball.servlet.GutterballValidationFilter.java
License:Open Source License
public void init(FilterConfig filterConfig) throws ServletException { HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) this.factoryProvider .get();// w w w . j a v a2 s . c o m SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory .getSessionFactory(); EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry() .getService(EventListenerRegistry.class); registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(this.listenerProvider.get()); registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(this.listenerProvider.get()); registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(this.listenerProvider.get()); }
From source file:org.candlepin.test.DatabaseTestFixture.java
License:Open Source License
/** * There's no way to really get Guice to perform injections on stuff that * the JpaPersistModule is creating, so we resort to grabbing the EntityManagerFactory * after the fact and adding the Validation EventListener ourselves. * @param injector//from ww w. j av a2 s. c om */ private void insertValidationEventListeners(Injector injector) { Provider<EntityManagerFactory> emfProvider = injector.getProvider(EntityManagerFactory.class); HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) emfProvider .get(); SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory .getSessionFactory(); EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry() .getService(EventListenerRegistry.class); Provider<BeanValidationEventListener> listenerProvider = injector .getProvider(BeanValidationEventListener.class); registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(listenerProvider.get()); registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(listenerProvider.get()); registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(listenerProvider.get()); }
From source file:org.granite.test.tide.hibernate4.data.TestHibernate4JPAChangeSetMerge.java
License:Open Source License
@Override protected void initPersistence() { Map<String, String> props = new HashMap<String, String>(); props.put("hibernate.dialect", org.hibernate.dialect.H2Dialect.class.getName()); props.put("hibernate.hbm2ddl.auto", "create-drop"); props.put("hibernate.show_sql", "true"); props.put("hibernate.connection.driver_class", org.h2.Driver.class.getName()); props.put("hibernate.connection.url", "jdbc:h2:mem:test-changesetmerge"); props.put("hibernate.connection.username", "sa"); props.put("hibernate.connection.password", ""); entityManagerFactory = Persistence.createEntityManagerFactory("hibernate4-changesetmerge-pu", props); try {//from ww w .j a v a 2 s . c o m SessionFactoryImpl sessionFactory = (SessionFactoryImpl) entityManagerFactory.getClass() .getMethod("getSessionFactory").invoke(entityManagerFactory); EventListenerRegistry registry = sessionFactory.getServiceRegistry() .getService(EventListenerRegistry.class); registry.setListeners(EventType.MERGE, new HibernateDataChangeMergeListener()); } catch (Exception e) { throw new RuntimeException("Could not init persistence", e); } }