@Test public void testDefaultFlushEventListener() throws Exception { EventListeners eventListeners = _sessionFactoryImpl.getEventListeners(); FlushEventListener[] flushEventListeners = eventListeners.getFlushEventListeners(); eventListeners.setFlushEventListeners( new FlushEventListener[] {new DefaultFlushEventListener()}); try { testNestableFlushEventListener(); Assert.fail(); } catch (IndexOutOfBoundsException ioobe) { } finally { eventListeners.setFlushEventListeners(flushEventListeners); } }
/** * Closes the session factory, releasing all held resources. * * <ol> * <li>cleans up used cache regions and "stops" the cache provider. * <li>close the JDBC connection * <li>remove the JNDI binding * </ol> * * Note: Be aware that the sessionfactory instance still can be a "heavy" object memory wise after * close() has been called. Thus it is important to not keep referencing the instance to let the * garbage collector release the memory. */ public void close() throws HibernateException { if (isClosed) { log.trace("already closed"); return; } log.info("closing"); isClosed = true; Iterator iter = entityPersisters.values().iterator(); while (iter.hasNext()) { EntityPersister p = (EntityPersister) iter.next(); if (p.hasCache()) { p.getCacheAccessStrategy().getRegion().destroy(); } } iter = collectionPersisters.values().iterator(); while (iter.hasNext()) { CollectionPersister p = (CollectionPersister) iter.next(); if (p.hasCache()) { p.getCacheAccessStrategy().getRegion().destroy(); } } if (settings.isQueryCacheEnabled()) { queryCache.destroy(); iter = queryCaches.values().iterator(); while (iter.hasNext()) { QueryCache cache = (QueryCache) iter.next(); cache.destroy(); } updateTimestampsCache.destroy(); } settings.getRegionFactory().stop(); if (settings.isAutoDropSchema()) { schemaExport.drop(false, true); } try { settings.getConnectionProvider().close(); } finally { SessionFactoryObjectFactory.removeInstance(uuid, name, properties); } observer.sessionFactoryClosed(this); eventListeners.destroyListeners(); }
private static void addEventListeners( PageContext pc, Configuration config, ORMConfiguration ormConfig, Map<String, CFCInfo> cfcs) throws PageException { if (!ormConfig.eventHandling()) return; String eventHandler = ormConfig.eventHandler(); AllEventListener listener = null; if (!StringUtil.isEmpty(eventHandler, true)) { // try { Component c = pc.loadComponent(eventHandler.trim()); listener = new AllEventListener(c); // config.setInterceptor(listener); // }catch (PageException e) {e.printStackTrace();} } config.setInterceptor(new InterceptorImpl(listener)); EventListeners listeners = config.getEventListeners(); // post delete List<EventListener> list = merge(listener, cfcs, EventListener.POST_DELETE); listeners.setPostDeleteEventListeners(list.toArray(new PostDeleteEventListener[list.size()])); // post insert list = merge(listener, cfcs, EventListener.POST_INSERT); listeners.setPostInsertEventListeners(list.toArray(new PostInsertEventListener[list.size()])); // post update list = merge(listener, cfcs, EventListener.POST_UPDATE); listeners.setPostUpdateEventListeners(list.toArray(new PostUpdateEventListener[list.size()])); // post load list = merge(listener, cfcs, EventListener.POST_LOAD); listeners.setPostLoadEventListeners(list.toArray(new PostLoadEventListener[list.size()])); // pre delete list = merge(listener, cfcs, EventListener.PRE_DELETE); listeners.setPreDeleteEventListeners(list.toArray(new PreDeleteEventListener[list.size()])); // pre insert // list=merge(listener,cfcs,EventListener.PRE_INSERT); // listeners.setPreInsertEventListeners(list.toArray(new PreInsertEventListener[list.size()])); // pre load list = merge(listener, cfcs, EventListener.PRE_LOAD); listeners.setPreLoadEventListeners(list.toArray(new PreLoadEventListener[list.size()])); // pre update // list=merge(listener,cfcs,EventListener.PRE_UPDATE); // listeners.setPreUpdateEventListeners(list.toArray(new PreUpdateEventListener[list.size()])); }
@Override @SuppressWarnings("unchecked") protected SessionFactory buildSessionFactory() throws Exception { // Create Configuration instance. Configuration config = newConfiguration(); DataSource dataSource = getDataSource(); if (dataSource != null) { // Make given DataSource available for SessionFactory configuration. configTimeDataSourceHolder.set(dataSource); } if (this.jtaTransactionManager != null) { // Make Spring-provided JTA TransactionManager available. configTimeTransactionManagerHolder.set(this.jtaTransactionManager); } if (this.cacheRegionFactory != null) { // Make Spring-provided Hibernate RegionFactory available. configTimeRegionFactoryHolder.set(this.cacheRegionFactory); } if (this.lobHandler != null) { // Make given LobHandler available for SessionFactory configuration. // Do early because because mapping resource might refer to custom types. configTimeLobHandlerHolder.set(this.lobHandler); } // Analogous to Hibernate EntityManager's Ejb3Configuration: // Hibernate doesn't allow setting the bean ClassLoader explicitly, // so we need to expose it as thread context ClassLoader accordingly. Thread currentThread = Thread.currentThread(); ClassLoader threadContextClassLoader = currentThread.getContextClassLoader(); boolean overrideClassLoader = (this.beanClassLoader != null && !this.beanClassLoader.equals(threadContextClassLoader)); if (overrideClassLoader) { currentThread.setContextClassLoader(this.beanClassLoader); } try { if (isExposeTransactionAwareSessionFactory()) { // Set Hibernate 3.1+ CurrentSessionContext implementation, // providing the Spring-managed Session as current Session. // Can be overridden by a custom value for the corresponding Hibernate property. config.setProperty( Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName()); } if (this.jtaTransactionManager != null) { // Set Spring-provided JTA TransactionManager as Hibernate property. config.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName()); config.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName()); } else { // Makes the Hibernate Session aware of the presence of a Spring-managed transaction. // Also sets connection release mode to ON_CLOSE by default. config.setProperty( Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName()); } if (this.entityInterceptor != null) { // Set given entity interceptor at SessionFactory level. config.setInterceptor(this.entityInterceptor); } if (this.namingStrategy != null) { // Pass given naming strategy to Hibernate Configuration. config.setNamingStrategy(this.namingStrategy); } if (this.typeDefinitions != null) { // Register specified Hibernate type definitions. Mappings mappings = config.createMappings(); for (TypeDefinitionBean typeDef : this.typeDefinitions) { mappings.addTypeDef( typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters()); } } if (this.filterDefinitions != null) { // Register specified Hibernate FilterDefinitions. for (FilterDefinition filterDef : this.filterDefinitions) { config.addFilterDefinition(filterDef); } } if (this.configLocations != null) { for (Resource resource : this.configLocations) { // Load Hibernate configuration from given location. config.configure(resource.getURL()); } } if (this.hibernateProperties != null) { // Add given Hibernate properties to Configuration. config.addProperties(this.hibernateProperties); } if (dataSource != null) { Class<?> providerClass = LocalDataSourceConnectionProvider.class; if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) { providerClass = TransactionAwareDataSourceConnectionProvider.class; } else if (config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) { providerClass = LocalJtaDataSourceConnectionProvider.class; } // Set Spring-provided DataSource as Hibernate ConnectionProvider. config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName()); } if (this.cacheRegionFactory != null) { // Expose Spring-provided Hibernate RegionFactory. config.setProperty( Environment.CACHE_REGION_FACTORY, LocalRegionFactoryProxy.class.getName()); } if (this.mappingResources != null) { // Register given Hibernate mapping definitions, contained in resource files. for (String mapping : this.mappingResources) { Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader); config.addInputStream(resource.getInputStream()); } } if (this.mappingLocations != null) { // Register given Hibernate mapping definitions, contained in resource files. for (Resource resource : this.mappingLocations) { config.addInputStream(resource.getInputStream()); } } if (this.cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from the file system. for (Resource resource : this.cacheableMappingLocations) { config.addCacheableFile(resource.getFile()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (Resource resource : this.mappingJarLocations) { config.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (Resource resource : this.mappingDirectoryLocations) { File file = resource.getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException( "Mapping directory location [" + resource + "] does not denote a directory"); } config.addDirectory(file); } } // Tell Hibernate to eagerly compile the mappings that we registered, // for availability of the mapping information in further processing. postProcessMappings(config); config.buildMappings(); if (this.entityCacheStrategies != null) { // Register cache strategies for mapped entities. for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames.hasMoreElements(); ) { String className = (String) classNames.nextElement(); String[] strategyAndRegion = StringUtils.commaDelimitedListToStringArray( this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { config.setCacheConcurrencyStrategy( className, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]); } } } if (this.collectionCacheStrategies != null) { // Register cache strategies for mapped collections. for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles.hasMoreElements(); ) { String collRole = (String) collRoles.nextElement(); String[] strategyAndRegion = StringUtils.commaDelimitedListToStringArray( this.collectionCacheStrategies.getProperty(collRole)); if (strategyAndRegion.length > 1) { config.setCollectionCacheConcurrencyStrategy( collRole, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]); } } } if (this.eventListeners != null) { // Register specified Hibernate event listeners. for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) { String listenerType = entry.getKey(); Object listenerObject = entry.getValue(); if (listenerObject instanceof Collection) { Collection<Object> listeners = (Collection<Object>) listenerObject; EventListeners listenerRegistry = config.getEventListeners(); Object[] listenerArray = (Object[]) Array.newInstance( listenerRegistry.getListenerClassFor(listenerType), listeners.size()); listenerArray = listeners.toArray(listenerArray); config.setListeners(listenerType, listenerArray); } else { config.setListener(listenerType, listenerObject); } } } // Perform custom post-processing in subclasses. postProcessConfiguration(config); // Build SessionFactory instance. logger.info("Building new Hibernate SessionFactory"); this.configuration = config; return newSessionFactory(config); } finally { if (dataSource != null) { configTimeDataSourceHolder.remove(); } if (this.jtaTransactionManager != null) { configTimeTransactionManagerHolder.remove(); } if (this.cacheRegionFactory != null) { configTimeRegionFactoryHolder.remove(); } if (this.lobHandler != null) { configTimeLobHandlerHolder.remove(); } if (overrideClassLoader) { // Reset original thread context ClassLoader. currentThread.setContextClassLoader(threadContextClassLoader); } } }