Example usage for org.hibernate.cfg Configuration setInterceptor

List of usage examples for org.hibernate.cfg Configuration setInterceptor

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration setInterceptor.

Prototype

public Configuration setInterceptor(Interceptor interceptor) 

Source Link

Document

Set the current Interceptor

Usage

From source file:generatehibernate.Test.java

public static void main(String[] args) {
    Configuration cfg = new Configuration().configure("/resources/hibernate.cfg.xml");
    cfg.setInterceptor(new UserInterceptor());
    SessionFactory sessionFactory = cfg.buildSessionFactory();

    Session session = sessionFactory.openSession();
    User user = new User();
    user.setUserName("Test interceptor");
    user.setFullName("azza hamdy");
    user.setDateOfBirth(new Date());
    user.setAddress("suez");
    user.setPhone("123456789");
    user.setEmail("test@mail.com");
    user.setRegistrationDate(new Date());
    user.setPassword("4815162342");
    user.setMobile("01025012646");
    session.save(user);/*from  w w  w .  j  a v  a  2 s  .c  o m*/
    session.persist(user);
    session.getTransaction().commit();
    session.close();
    System.out.println("Insertion Done");
}

From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateConfigurations.java

License:Open Source License

/**
 * Creates a SessionFactory./*  ww w . j ava 2  s.  c om*/
 * 
 * @param pathToCfg
 *        Path to the hibernate configuration file.
 * @param dbSchema
 *        Db schema.
 * @param sessionInterceptor
 *        Hibernate session interceptor.
 * @param hibernateMappingsPath
 *        Path to file that lists files indexing hbm files this session factory
 *        should be configured with
 * 
 * @return Returns the session factory.
 * 
 * @throws InitializationException
 *         If the creation of the SessionFactory fails.
 */
@SuppressWarnings("nls")
static SessionFactory createSessionFactory(String pathToCfg, String dbSchema, String sessionInterceptor,
        String hibernateMappingsPath) throws InitializationException {
    try {
        Configuration conf = new Configuration();

        Interceptor interceptor = getInterceptor(sessionInterceptor);
        if (interceptor != null) {
            conf.setInterceptor(interceptor);
        }

        conf.setProperty(SCHEMA_PROPERTY, dbSchema);

        List<String> hbms = getHibernateMappingsIfAvailable(hibernateMappingsPath);
        for (String entityMapping : hbms) {
            LOGGER.debug("Adding " + entityMapping + " to the session factory configuration.");
            conf.addResource(entityMapping);
        }

        conf.configure(pathToCfg);

        conf.getEntityTuplizerFactory().registerDefaultTuplizerClass(EntityMode.POJO,
                Bo2PojoEntityTuplizer.class);
        SessionFactory sessionFactory = conf.buildSessionFactory();
        ((SessionFactoryImpl) sessionFactory).registerEntityNameResolver(Bo2EntityNameResolver.INSTANCE,
                EntityMode.POJO);
        sessionFactory.getStatistics().setStatisticsEnabled(true);
        return sessionFactory;
    } catch (HibernateException e) {
        throw new InitializationException(e);
    }
}

From source file:griffon.plugins.hibernate3.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyEntityInterceptor(Configuration config) {
    Object entityInterceptor = ConfigUtils.getConfigValue(sessionConfig, ENTITY_INTERCEPTOR);
    if (entityInterceptor instanceof Class) {
        config.setInterceptor((Interceptor) newInstanceOf((Class) entityInterceptor));
    } else if (entityInterceptor instanceof String) {
        config.setInterceptor((Interceptor) newInstanceOf((String) entityInterceptor));
    }//  ww w  .j a va2  s.c  o  m
}

From source file:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java

License:Open Source License

protected SessionFactory buildSessionFactory() throws Exception {
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] BEGIN");
    SessionFactory sf = null;/*ww w  .  j  av  a2  s.  c  o  m*/

    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource currentDataSource = getCurrentDataSource();
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '"
            + RepositoryManager.getCurrentRepository() + "' -- Got currentDataSource: " + currentDataSource);

    if (currentDataSource == null) {
        throw new IllegalStateException("Null DataSource!");
    }

    // Make given DataSource available for SessionFactory configuration.
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Thread '"
            + Thread.currentThread().getName() + "' -- Setting DataSource for current thread: "
            + currentDataSource);
    CONFIG_TIME_DS_HOLDER.set(currentDataSource);

    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        CONFIG_TIME_TM_HOLDER.set(this.jtaTransactionManager);
    }

    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        CONFIG_TIME_LOB_HANDLER_HOLDER.set(this.lobHandler);
    }

    try {
        // Set connection release mode "on_close" as default.
        // This was the case for Hibernate 3.0; Hibernate 3.1 changed
        // it to "auto" (i.e. "after_statement" or "after_transaction").
        // However, for Spring's resource management (in particular for
        // HibernateTransactionManager), "on_close" is the better default.
        config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString());

        if (!isExposeTransactionAwareSessionFactory()) {
            // Not exposing a SessionFactory proxy with transaction-aware
            // getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext
            // implementation instead, providing the Spring-managed Session that way.
            // Can be overridden by a custom value for corresponding Hibernate property.
            config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,
                    "org.springframework.orm.hibernate3.SpringSessionContext");
        }

        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 (int i = 0; i < this.typeDefinitions.length; i++) {
                TypeDefinitionBean typeDef = this.typeDefinitions[i];
                mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (int i = 0; i < this.filterDefinitions.length; i++) {
                config.addFilterDefinition(this.filterDefinitions[i]);
            }
        }

        if (this.configLocations != null) {
            for (int i = 0; i < this.configLocations.length; i++) {
                // Load Hibernate configuration from given location.
                config.configure(this.configLocations[i].getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            config.addProperties(this.hibernateProperties);
        }

        if (currentDataSource != null) {
            boolean actuallyTransactionAware = (this.useTransactionAwareDataSource
                    || currentDataSource instanceof TransactionAwareDataSourceProxy);
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            config.setProperty(Environment.CONNECTION_PROVIDER,
                    actuallyTransactionAware ? TransactionAwareDataSourceConnectionProvider.class.getName()
                            : RoutingLocalDataSourceConnectionProvider.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (int i = 0; i < this.mappingLocations.length; i++) {
                config.addInputStream(this.mappingLocations[i].getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (int i = 0; i < this.cacheableMappingLocations.length; i++) {
                config.addCacheableFile(this.cacheableMappingLocations[i].getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (int i = 0; i < this.mappingJarLocations.length; i++) {
                Resource resource = this.mappingJarLocations[i];
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (int i = 0; i < this.mappingDirectoryLocations.length; i++) {
                File file = this.mappingDirectoryLocations[i].getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException("Mapping directory location ["
                            + this.mappingDirectoryLocations[i] + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        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<?, ?> entry : this.eventListeners.entrySet()) {
                Assert.isTrue(entry.getKey() instanceof String,
                        "Event listener key needs to be of type String");
                String listenerType = (String) entry.getKey();
                Object listenerObject = entry.getValue();

                if (listenerObject instanceof Collection) {
                    Collection<?> listeners = (Collection<?>) 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.debug(
                "[RoutingLocalSessionFactoryBean::buildSessionFactory] Building new Hibernate SessionFactory.");
        this.configuration = config;

        SessionFactoryProxy sessionFactoryProxy = new SessionFactoryProxy(
                repositoryManager.getDefaultRepository().getId());
        for (Repository repository : repositoryManager.getRepositories()) {
            logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '"
                    + repository.getId() + "' -- Building SessionFactory...");

            RepositoryManager.setCurrentRepository(repository.getId());
            sessionFactoryProxy.addSessionFactory(repository.getId(), newSessionFactory(config));
        }
        RepositoryManager.setCurrentRepository(repositoryManager.getDefaultRepository().getId());
        sf = sessionFactoryProxy;
    } finally {
        if (currentDataSource != null) {
            // Reset DataSource holder.
            CONFIG_TIME_DS_HOLDER.set(null);
        }

        if (this.jtaTransactionManager != null) {
            // Reset TransactionManager holder.
            CONFIG_TIME_TM_HOLDER.set(null);
        }

        if (this.lobHandler != null) {
            // Reset LobHandler holder.
            CONFIG_TIME_LOB_HANDLER_HOLDER.set(null);
        }
    }

    // Execute schema update if requested.
    if (this.schemaUpdate) {
        updateDatabaseSchema();
    }

    return sf;
}

From source file:lucee.runtime.orm.hibernate.HibernateORMEngine.java

License:Open Source License

private static void addEventListeners(PageContext pc, SessionFactoryData data, Key key) throws PageException {
    if (!data.getORMConfiguration().eventHandling())
        return;// w w w . j  ava  2s.co m
    String eventHandler = data.getORMConfiguration().eventHandler();
    AllEventListener listener = null;
    if (!Util.isEmpty(eventHandler, true)) {
        //try {
        Component c = pc.loadComponent(eventHandler.trim());

        listener = new AllEventListener(c);
        //config.setInterceptor(listener);
        //}catch (PageException e) {e.printStackTrace();}
    }
    Configuration conf = data.getConfiguration(key);
    conf.setInterceptor(new InterceptorImpl(listener));
    EventListeners listeners = conf.getEventListeners();
    Map<String, CFCInfo> cfcs = data.getCFCs(key);
    // post delete
    List<EventListener> list = merge(listener, cfcs, CommonUtil.POST_DELETE);
    listeners.setPostDeleteEventListeners(list.toArray(new PostDeleteEventListener[list.size()]));

    // post insert
    list = merge(listener, cfcs, CommonUtil.POST_INSERT);
    listeners.setPostInsertEventListeners(list.toArray(new PostInsertEventListener[list.size()]));

    // post update
    list = merge(listener, cfcs, CommonUtil.POST_UPDATE);
    listeners.setPostUpdateEventListeners(list.toArray(new PostUpdateEventListener[list.size()]));

    // post load
    list = merge(listener, cfcs, CommonUtil.POST_LOAD);
    listeners.setPostLoadEventListeners(list.toArray(new PostLoadEventListener[list.size()]));

    // pre delete
    list = merge(listener, cfcs, CommonUtil.PRE_DELETE);
    listeners.setPreDeleteEventListeners(list.toArray(new PreDeleteEventListener[list.size()]));

    // pre insert
    //list=merge(listener,cfcs,CommonUtil.PRE_INSERT);
    //listeners.setPreInsertEventListeners(list.toArray(new PreInsertEventListener[list.size()]));

    // pre load
    list = merge(listener, cfcs, CommonUtil.PRE_LOAD);
    listeners.setPreLoadEventListeners(list.toArray(new PreLoadEventListener[list.size()]));

    // pre update
    //list=merge(listener,cfcs,CommonUtil.PRE_UPDATE);
    //listeners.setPreUpdateEventListeners(list.toArray(new PreUpdateEventListener[list.size()]));
}

From source file:org.bonitasoft.engine.persistence.AbstractHibernatePersistenceService.java

License:Open Source License

/**
 * @param name/*from   www  .j a va2 s. co  m*/
 * @param hbmConfigurationProvider
 * @param likeEscapeCharacter
 * @param logger
 * @param sequenceManager
 * @param datasource
 * @param enableWordSearch
 * @param wordSearchExclusionMappings
 * @throws SPersistenceException
 * @throws ClassNotFoundException
 */
public AbstractHibernatePersistenceService(final String name,
        final HibernateConfigurationProvider hbmConfigurationProvider,
        final Properties extraHibernateProperties, final String likeEscapeCharacter,
        final TechnicalLoggerService logger, final SequenceManager sequenceManager, final DataSource datasource,
        final boolean enableWordSearch, final Set<String> wordSearchExclusionMappings)
        throws SPersistenceException, ClassNotFoundException {
    super(name, likeEscapeCharacter, sequenceManager, datasource, enableWordSearch, wordSearchExclusionMappings,
            logger);
    orderByCheckingMode = getOrderByCheckingMode();
    Configuration configuration;
    try {
        configuration = hbmConfigurationProvider.getConfiguration();
        if (extraHibernateProperties != null) {
            configuration.addProperties(extraHibernateProperties);
        }
    } catch (final ConfigurationException e) {
        throw new SPersistenceException(e);
    }
    final String dialect = configuration.getProperty("hibernate.dialect");
    if (dialect != null) {
        if (dialect.contains("PostgreSQL")) {
            configuration.setInterceptor(new PostgresInterceptor());
        } else if (dialect.contains("SQLServer")) {
            configuration.setInterceptor(new SQLServerInterceptor());
        }
    }
    final String className = configuration.getProperty("hibernate.interceptor");
    if (className != null && !className.isEmpty()) {
        try {
            final Interceptor interceptor = (Interceptor) Class.forName(className).newInstance();
            configuration.setInterceptor(interceptor);
        } catch (final ClassNotFoundException cnfe) {
            throw new SPersistenceException(cnfe);
        } catch (final InstantiationException e) {
            throw new SPersistenceException(e);
        } catch (final IllegalAccessException e) {
            throw new SPersistenceException(e);
        }

    }

    sessionFactory = configuration.buildSessionFactory();
    statistics = sessionFactory.getStatistics();

    final Iterator<PersistentClass> classMappingsIterator = configuration.getClassMappings();
    classMapping = new ArrayList<Class<? extends PersistentObject>>();
    while (classMappingsIterator.hasNext()) {
        classMapping.add(classMappingsIterator.next().getMappedClass());
    }

    classAliasMappings = hbmConfigurationProvider.getClassAliasMappings();

    interfaceToClassMapping = hbmConfigurationProvider.getInterfaceToClassMapping();

    mappingExclusions = hbmConfigurationProvider.getMappingExclusions();

    cacheQueries = hbmConfigurationProvider.getCacheQueries();
}

From source file:org.chenillekit.hibernate.services.impl.HibernateInterceptorConfigurer.java

License:Apache License

/**
 * Passed the configuration so as to make changes.
 *///from   w  w w  .  j  a  v a2s.  c o  m
public void configure(Configuration configuration) {
    configuration.setInterceptor(_interceptor);
}

From source file:org.codehaus.griffon.runtime.hibernate3.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyEntityInterceptor(Configuration config) {
    Object entityInterceptor = getConfigValue(sessionConfig, ENTITY_INTERCEPTOR, null);
    if (entityInterceptor instanceof Class) {
        config.setInterceptor((Interceptor) newInstanceOf((Class) entityInterceptor));
    } else if (entityInterceptor instanceof String) {
        config.setInterceptor((Interceptor) newInstanceOf((String) entityInterceptor));
    }/*from   www.  java 2 s .  co m*/
}

From source file:org.jboss.hibernate.jmx.Hibernate.java

License:Open Source License

private final Configuration buildConfiguration() throws Exception {
    log.debug("Building SessionFactory; " + this);

    Configuration cfg = new Configuration();
    cfg.getProperties().clear(); // avoid reading hibernate.properties and Sys-props

    // Handle custom listeners....
    ListenerInjector listenerInjector = generateListenerInjectorInstance();
    if (listenerInjector != null) {
        listenerInjector.injectListeners(getServiceName(), cfg);
    }/* ww w. java2s. com*/

    // Handle config settings....
    transferSettings(cfg.getProperties());

    // Handle mappings....
    handleMappings(cfg);

    // Handle interceptor....
    Interceptor interceptorInstance = generateInterceptorInstance();
    if (interceptorInstance != null) {
        cfg.setInterceptor(interceptorInstance);
    }

    return cfg;
}

From source file:org.openbravo.base.model.ModelSessionFactoryController.java

License:Open Source License

@Override
protected void setInterceptor(Configuration configuration) {
    configuration.setInterceptor(new LocalInterceptor());
}