List of usage examples for org.hibernate.cfg Configuration setInterceptor
public Configuration setInterceptor(Interceptor interceptor)
From source file:com.db4o.drs.hibernate.impl.ObjectLifeCycleEventsListenerImpl.java
License:Open Source License
private void resetListeners(Configuration cfg) { cfg.setInterceptor(EmptyInterceptor.INSTANCE); EventListeners el = cfg.getEventListeners(); PostUpdateEventListener[] o2 = el.getPostUpdateEventListeners(); PostUpdateEventListener[] r2 = (PostUpdateEventListener[]) Util.removeElement(o2, this); if ((o2.length - r2.length) != 1) throw new RuntimeException("can't remove"); el.setPostUpdateEventListeners(r2);//from ww w . j a va2 s.c o m PreDeleteEventListener[] o3 = el.getPreDeleteEventListeners(); PreDeleteEventListener[] r3 = (PreDeleteEventListener[]) Util.removeElement(o3, this); if ((o3.length - r3.length) != 1) throw new RuntimeException("can't remove"); el.setPreDeleteEventListeners(r3); PostInsertEventListener[] o4 = el.getPostInsertEventListeners(); PostInsertEventListener[] r4 = (PostInsertEventListener[]) Util.removeElement(o4, this); if ((o4.length - r4.length) != 1) throw new RuntimeException("can't remove"); FlushEventListener[] o5 = el.getFlushEventListeners(); FlushEventListener[] r5 = (FlushEventListener[]) Util.removeElement(o5, this); if ((o5.length - r5.length) != 1) throw new RuntimeException("can't remove"); el.setPostInsertEventListeners(r4); }
From source file:com.db4o.drs.hibernate.impl.ObjectLifeCycleEventsListenerImpl.java
License:Open Source License
private void setListeners(Configuration cfg) { cfg.setInterceptor(this); EventListeners el = cfg.getEventListeners(); el.setPostUpdateEventListeners(//from w w w . j a va2 s . c o m (PostUpdateEventListener[]) Util.add(el.getPostUpdateEventListeners(), this)); el.setPostInsertEventListeners( (PostInsertEventListener[]) Util.add(el.getPostInsertEventListeners(), this)); el.setPreDeleteEventListeners((PreDeleteEventListener[]) Util.add(el.getPreDeleteEventListeners(), this)); el.setFlushEventListeners((FlushEventListener[]) Util.add(el.getFlushEventListeners(), this)); }
From source file:com.frameworkset.common.poolman.hibernate.LocalSessionFactoryBean.java
License:Apache License
@Override @SuppressWarnings("unchecked") protected SessionFactory buildSessionFactory() throws Exception { // Create Configuration instance. Configuration config = newConfiguration(); DataSource dataSource = getDataSource(); if (dataSource != null) { this.configTimeDataSourceHolder.set(dataSource); }/*from ww w . ja v a 2 s . c om*/ // 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)); try { if (overrideClassLoader) { currentThread.setContextClassLoader(this.beanClassLoader); } 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.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. Properties temp = new Properties(); temp.putAll(this.hibernateProperties); config.addProperties(temp); } if (dataSource != null) { Class providerClass = LocalDataSourceConnectionProvider.class; config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.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 = SimpleStringUtil .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { // method signature declares return type as Configuration on Hibernate 3.6 // but as void on Hibernate 3.3 and 3.5 Method setCacheConcurrencyStrategy = Configuration.class .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class); ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config, new Object[] { 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 = SimpleStringUtil .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 (overrideClassLoader) { // Reset original thread context ClassLoader. currentThread.setContextClassLoader(threadContextClassLoader); } configTimeDataSourceHolder.set(null); } }
From source file:com.maydesk.base.util.CledaConnector.java
License:Mozilla Public License
private void createSessionFactory() { Properties props = new Properties(); try {// w ww .jav a 2s. c om Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/maydesk_db"); props.put("hibernate.connection.datasource", ds); } catch (NamingException e) { e.printStackTrace(); } props.put("hibernate.cglib.use_reflection_optimizer", true); props.put("hibernate.show_sql", false); props.put("hibernate.hbm2ddl.auto", "update"); props.put("transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory"); props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); // Create config Configuration config = new Configuration(); config.setProperties(props); config.setInterceptor(new AuditInterceptor()); config.setNamingStrategy(new ImprovedNamingStrategy()); config.setProperties(props); // registering model registerModels(config, "com.maydesk.base.model"); registerModels(config, "com.maydesk.social.model"); ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder(); ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(props).buildServiceRegistry(); sessionFactory = config.buildSessionFactory(serviceRegistry); }
From source file:com.redhat.rhn.common.hibernate.ConnectionManager.java
License:Open Source License
/** * Create a SessionFactory, loading the hbm.xml files from the specified * location./* w w w. j a va2s . c o m*/ * @param packageNames Package name to be searched. */ private void createSessionFactory() { if (sessionFactory != null && !sessionFactory.isClosed()) { return; } List<String> hbms = new LinkedList<String>(); for (Iterator<String> iter = packageNames.iterator(); iter.hasNext();) { String pn = iter.next(); hbms.addAll(FinderFactory.getFinder(pn).find("hbm.xml")); if (LOG.isDebugEnabled()) { LOG.debug("Found: " + hbms); } } try { Configuration config = new Configuration(); /* * Let's ask the RHN Config for all properties that begin with * hibernate.* */ LOG.info("Adding hibernate properties to hibernate Configuration"); Properties hibProperties = Config.get().getNamespaceProperties("hibernate"); hibProperties.put("hibernate.connection.username", Config.get().getString(ConfigDefaults.DB_USER)); hibProperties.put("hibernate.connection.password", Config.get().getString(ConfigDefaults.DB_PASSWORD)); hibProperties.put("hibernate.connection.url", ConfigDefaults.get().getJdbcConnectionString()); config.addProperties(hibProperties); // Force the use of our txn factory if (config.getProperty(Environment.TRANSACTION_STRATEGY) != null) { throw new IllegalArgumentException("The property " + Environment.TRANSACTION_STRATEGY + " can not be set in a configuration file;" + " it is set to a fixed value by the code"); } for (Iterator<String> i = hbms.iterator(); i.hasNext();) { String hbmFile = i.next(); if (LOG.isDebugEnabled()) { LOG.debug("Adding resource " + hbmFile); } config.addResource(hbmFile); } if (configurators != null) { for (Iterator<Configurator> i = configurators.iterator(); i.hasNext();) { Configurator c = i.next(); c.addConfig(config); } } // add empty varchar warning interceptor EmptyVarcharInterceptor interceptor = new EmptyVarcharInterceptor(); interceptor.setAutoConvert(true); config.setInterceptor(interceptor); sessionFactory = config.buildSessionFactory(); } catch (HibernateException e) { LOG.error("FATAL ERROR creating HibernateFactory", e); } }
From source file:com.speedment.orm.examples.hares.AbstractTest.java
License:Open Source License
private SessionFactory newSessionFactory() { Properties properties = getProperties(); Configuration configuration = new Configuration().addProperties(properties); for (Class<?> entityClass : entities()) { configuration.addAnnotatedClass(entityClass); }/*from w ww . j a v a 2 s.c o m*/ String[] packages = packages(); if (packages != null) { for (String scannedPackage : packages) { configuration.addPackage(scannedPackage); } } Interceptor interceptor = interceptor(); if (interceptor != null) { configuration.setInterceptor(interceptor); } return configuration .buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(properties).build()); }
From source file:de.cosmocode.palava.jpa.hibernate.DefaultHibernateService.java
License:Apache License
@Override public void initialize() { final Configuration configuration = new AnnotationConfiguration(); LOG.debug("Adding hibernate schema: {}", schema); configuration.addURL(schema);//from ww w . j a va 2s . co m LOG.debug("Adding hibernate config file: {}", config); configuration.configure(config); if (interceptor == null) { LOG.info("No interceptor configured"); } else { LOG.info("Using {} as interceptor", interceptor); configuration.setInterceptor(interceptor); } if (propagateEvents) { LOG.info("Registering event listeners"); for (Entry<String, Class<?>> entry : LISTENERS.entrySet()) { final String event = entry.getKey(); final Class<?> type = entry.getValue(); final Key<?> key = Key.get(type, event); final Object listener = registry.proxy(key); LOG.info("Registering {} for {}", listener, event); configuration.setListener(event, listener); } } else { LOG.info("Events are not propagated through the registry"); } LOG.debug("Building session factory"); this.factory = configuration.buildSessionFactory(); statistics.setSessionFactory(factory); statistics.setStatisticsEnabled(true); mBeanService.register(statistics, "name", name); }
From source file:ee.ria.xroad.common.db.HibernateUtil.java
License:Open Source License
private static Configuration getDefaultConfiguration(String name, Interceptor interceptor) throws Exception { String databaseProps = SystemProperties.getDatabasePropertiesFile(); Properties extraProperties = new PrefixedProperties(name + "."); try (InputStream in = new FileInputStream(databaseProps)) { extraProperties.load(in);/*w w w . j a va2s.c o m*/ } Configuration configuration = new Configuration(); if (interceptor != null) { configuration.setInterceptor(interceptor); } configuration.addProperties(extraProperties); return configuration; }
From source file:es.jpons.persistence.util.TemporalHibernateUtil.java
License:Open Source License
public static synchronized Session getSession(Properties configuration, List<Class> annotatedClasses) { // if(instance==null){ // log.trace("Creating instance from properties"); //// setProperties(configuration); // instance = new TemporalHibernateUtil(); // }/*from ww w .j a va2 s .com*/ Configuration cfg = new AnnotationConfiguration();//.setProperties(configuration);//Configuration(); cfg.setProperties(configuration); cfg.addPackage(configuration.getProperty("package.persistence")); // esta funcion parece interesante //cfg.addSqlFunction(rn, null); log.trace("Registering temporal interceptor"); cfg.setInterceptor(new TemporalInterceptor()); for (Class c : annotatedClasses) { cfg.addAnnotatedClass(c); } log.trace("Configuration from properties file"); if (factory == null) { factory = cfg.buildSessionFactory(); } log.trace("Session factory created"); return factory.openSession(); }
From source file:generatehibernate.GenerateHibernate.java
/** * @param args the command line arguments *//*from w ww . ja v a2 s . c o m*/ public static void main(String[] args) { // TODO code application logic here Configuration cfg = new Configuration().configure("/resources/hibernate.cfg.xml"); cfg.setInterceptor(new UserInterceptor()); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); Buyer br = new Buyer(); Seller sl = new Seller(); User user = new User(); Product proud = new Product(); //Product proud1=new Product(); Category cate = new Category(); BuyerBidProduct BuyerbidProduct = new BuyerBidProduct(); BuyerBuyProduct BuyerbuyProuduct = new BuyerBuyProduct(); user.setUserName("azza"); user.setFullName("azza hamdy"); user.setDateOfBirth(new Date()); user.setAddress("suez"); user.setPhone("123456789"); user.setEmail("azza@mail.com"); user.setRegistrationDate(new Date()); user.setPassword("4815162342"); user.setMobile("01025012646"); br.setUser(user); br.setValue("Tea"); sl.setUser(user); sl.setValue("teaaa"); proud.setName("product1"); proud.setQuantity(5); proud.setExpirationDate(new Date()); proud.setDescription("firstproduct insert"); proud.setFinishDate(new Date()); proud.setManufacturingName("Hibernare"); proud.setOfferedDate(new Date()); proud.setManufacturingDate(new Date()); proud.setSeller(sl); Product proud2 = new Product(); proud2.setName("product4"); proud2.setQuantity(5); proud2.setExpirationDate(new Date()); proud2.setDescription("firstproduct insert"); proud2.setFinishDate(new Date()); proud2.setManufacturingName("Hibernare"); proud2.setOfferedDate(new Date()); proud2.setManufacturingDate(new Date()); proud2.setSeller(sl); cate.setValue("cate2"); cate.setDescription("blala"); cate.getProducts().add(proud2); BuyerbidProduct.setBuyer(br); BuyerbidProduct.setProduct(proud2); BuyerbidProduct.setDate(new Date()); BuyerbidProduct.setAmount(4f); BuyerbidProduct.setQuantity(2); BuyerbuyProuduct.setBuyer(br); BuyerbuyProuduct.setProduct(proud); BuyerbuyProuduct.setPaymentDate(new Date()); BuyerbuyProuduct.setQuantity(4); BuyerbuyProuduct.setAmount(3f); session.save(user); session.save(sl); session.save(br); session.save(proud); // session.save(proud1); session.save(proud2); session.save(cate); BuyerbidProduct.setId(new BuyerBidProductId(br.getId(), proud2.getId())); session.save(BuyerbidProduct); BuyerbuyProuduct.setId(new BuyerBuyProductId(br.getId(), proud.getId())); session.save(BuyerbuyProuduct); session.beginTransaction(); //session.persist(br); //session.persist(sl); session.persist(BuyerbidProduct); session.persist(BuyerbuyProuduct); session.getTransaction().commit(); session.close(); System.out.println("Insertion Done"); }