org.hibernate.cfg.Configuration Java Examples

The following examples show how to use org.hibernate.cfg.Configuration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InHibernate.java    From Transwarp-Sample-Code with MIT License 8 votes vote down vote up
public static void main(String[] args) {
    String path = "hibernate.cfg.xml";
    Configuration cfg = new Configuration().configure(path);

    SessionFactory sessionFactory = cfg.buildSessionFactory();

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    User user = new User();
    user.setId("443");
    user.setName("baa");
    session.save(user);
    // session.close();
    session.getTransaction().commit();
    sessionFactory.close();
}
 
Example #2
Source File: MigrationTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testSimpleColumnAddition() {
	String resource1 = "org/hibernate/test/schemaupdate/1_Version.hbm.xml";
	String resource2 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml";

	Configuration v1cfg = new Configuration();
	v1cfg.addResource( resource1 );
	new SchemaExport( v1cfg ).execute( false, true, true, false );

	SchemaUpdate v1schemaUpdate = new SchemaUpdate( v1cfg );
	v1schemaUpdate.execute( true, true );

	assertEquals( 0, v1schemaUpdate.getExceptions().size() );

	Configuration v2cfg = new Configuration();
	v2cfg.addResource( resource2 );

	SchemaUpdate v2schemaUpdate = new SchemaUpdate( v2cfg );
	v2schemaUpdate.execute( true, true );
	assertEquals( 0, v2schemaUpdate.getExceptions().size() );

}
 
Example #3
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(Configuration cfg) {
    super.configure(cfg);
    cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName());
    cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;");
    cfg.setProperty(Environment.USER, "sa");
    cfg.setProperty(Environment.PASS, "");
    cfg.setProperty(Environment.CACHE_REGION_PREFIX, "");
    cfg.setProperty(Environment.GENERATE_STATISTICS, "true");

    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
    cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName());
    
    cfg.setProperty("hibernate.cache.redisson.item.eviction.max_entries", "100");
    cfg.setProperty("hibernate.cache.redisson.item.expiration.time_to_live", "1500");
    cfg.setProperty("hibernate.cache.redisson.item.expiration.max_idle_time", "1000");
}
 
Example #4
Source File: WikiHibernateUtil.java    From dkpro-jwpl with Apache License 2.0 6 votes vote down vote up
public static SessionFactory getSessionFactory(DatabaseConfiguration config) {

        if (config.getLanguage() == null) {
            throw new ExceptionInInitializerError("Database configuration error. 'Language' is empty.");
        }
        else if (config.getHost() == null) {
            throw new ExceptionInInitializerError("Database configuration error. 'Host' is empty.");
        }
        else if (config.getDatabase() == null) {
            throw new ExceptionInInitializerError("Database configuration error. 'Database' is empty.");
        }

        String uniqueSessionKey = config.getLanguage().toString() + config.getHost() + config.getDatabase();
        if (!sessionFactoryMap.containsKey(uniqueSessionKey)) {
        	Configuration configuration = getConfiguration(config);
            StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
            sessionFactoryMap.put(uniqueSessionKey, sessionFactory);
        }
        return sessionFactoryMap.get(uniqueSessionKey);
    }
 
Example #5
Source File: HibernateDataSource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void addDatamart(FileDataSourceConfiguration configuration, boolean extendClassLoader) {
	Configuration cfg = null;	
	SessionFactory sf = null;
	
	if(configuration.getFile() == null) return;
	
	cfg = buildEmptyConfiguration();
	configurationMap.put(configuration.getModelName(), cfg);
	
	if (extendClassLoader){
		updateCurrentClassLoader(configuration.getFile());
	}	
	
	cfg.addJar(configuration.getFile());
	
	try {
		compositeHibernateConfiguration.addJar(configuration.getFile());
	} catch (Throwable t) {
		throw new RuntimeException("Cannot add datamart", t);
	}
	
	sf = cfg.buildSessionFactory();
	sessionFactoryMap.put(configuration.getModelName(), sf);		
}
 
Example #6
Source File: ExtendsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testMissingSuper() {
	Configuration cfg = new Configuration();

	try {
		cfg.addResource( getBaseForMappings() + "extendshbm/Customer.hbm.xml" );
		assertNull(
				"cannot be in the configuration yet!",
				cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" )
		);
		cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" );

		cfg.buildSessionFactory();

		fail( "Should not be able to build sessionfactory without a Person" );
	}
	catch ( HibernateException e ) {

	}

}
 
Example #7
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocalSessionFactoryBeanWithCustomSessionFactory() throws Exception {
	final SessionFactory sessionFactory = mock(SessionFactory.class);
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			return sessionFactory;
		}
	};
	sfb.setMappingResources(new String[0]);
	sfb.setDataSource(new DriverManagerDataSource());
	sfb.setExposeTransactionAwareSessionFactory(false);
	sfb.afterPropertiesSet();
	assertTrue(sessionFactory == sfb.getObject());
	sfb.destroy();
	verify(sessionFactory).close();
}
 
Example #8
Source File: HibernateUtil.java    From serverless with Apache License 2.0 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    if (null != sessionFactory)
        return sessionFactory;
    
    Configuration configuration = new Configuration();

    String jdbcUrl = "jdbc:mysql://"
            + System.getenv("RDS_HOSTNAME")
            + "/"
            + System.getenv("RDS_DB_NAME");
    
    configuration.setProperty("hibernate.connection.url", jdbcUrl);
    configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME"));
    configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD"));

    configuration.configure();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    try {
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        System.err.println("Initial SessionFactory creation failed." + e);
        throw new ExceptionInInitializerError(e);
    }
    return sessionFactory;
}
 
Example #9
Source File: BaseCoreFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected Configuration constructConfiguration() {
  Configuration configuration = new Configuration();
  configuration.setProperty( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
  configuration.setProperty( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
  if ( createSchema() ) {
    configuration.setProperty( Environment.HBM2DDL_AUTO, "update" );
    final String secondSchemaName = createSecondSchema();
    if ( StringHelper.isNotEmpty( secondSchemaName ) ) {
      if ( !( getDialect() instanceof H2Dialect ) ) {
        throw new UnsupportedOperationException( "Only H2 dialect supports creation of second schema." );
      }
      Helper.createH2Schema( secondSchemaName, configuration );
    }
  }
  configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE );
  configuration.setProperty( Environment.DIALECT, getDialect().getClass().getName() );
  return configuration;
}
 
Example #10
Source File: HibernateUtil.java    From yeti with MIT License 6 votes vote down vote up
private static SessionFactory buildSessionAnnotationFactory() {
    try {
        Properties dbProps = ConfigSettings.getDatabaseProperties();
        
        Configuration configuration = new Configuration();
        configuration.setProperties(dbProps);
        configuration.configure("hibernate-annotation.cfg.xml");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        return sessionFactory;
    } catch (HibernateException ex) {
        Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example #11
Source File: CacheHibernateStoreSessionListenerSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected Factory<CacheStoreSessionListener> sessionListenerFactory() {
    return new Factory<CacheStoreSessionListener>() {
        @Override public CacheStoreSessionListener create() {
            CacheHibernateStoreSessionListener lsnr = new CacheHibernateStoreSessionListener();

            SessionFactory sesFactory = new Configuration().
                setProperty("hibernate.connection.url", URL).
                addAnnotatedClass(Table1.class).
                addAnnotatedClass(Table2.class).
                buildSessionFactory();

            lsnr.setSessionFactory(sesFactory);

            return lsnr;
        }
    };
}
 
Example #12
Source File: BaseCoreFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void rebuildSessionFactory(Consumer<Configuration> configurationAdapter) {
  if ( sessionFactory == null ) {
    return;
  }
  try {
    sessionFactory.close();
    sessionFactory = null;
    configuration = null;
    serviceRegistry.destroy();
    serviceRegistry = null;
  }
  catch (Exception ignore) {
  }

  buildSessionFactory( configurationAdapter );
}
 
Example #13
Source File: HibernateUtil.java    From journaldev with MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
    	Configuration configuration = new Configuration();
    	configuration.configure("hibernate.cfg.xml");
    	System.out.println("Hibernate Configuration loaded");
    	
    	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    	System.out.println("Hibernate serviceRegistry created");
    	
    	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    	
        return sessionFactory;
    }
    catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example #14
Source File: ITCaseDailyStatHsqldbSchema.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    final Configuration config = new Configuration().setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
            .setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver").setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:baseball")
            .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.connection.pool_size", "1")
            .setProperty("hibernate.connection.autocommit", "true").setProperty("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider")
            .setProperty("hibernate.hbm2ddl.auto", "create-drop").setProperty("hibernate.show_sql", "true").addClass(DailyStat.class);

    HibernateUtil.setSessionFactory(config.buildSessionFactory());

    // uncomment the following if you want to launch a the dbmanager gui (while debugging through this class probably)
    /*
     * Runnable r = new Runnable() {
     * 
     * @Override public void run() { org.hsqldb.util.DatabaseManagerSwing.main(new String[0]); } }; Thread th = new Thread(r); th.setDaemon(true); th.start();
     */}
 
Example #15
Source File: ExtendsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testJoinedSubclassAndEntityNamesOnly() {
	Configuration cfg = new Configuration();

	try {
		cfg.addResource( getBaseForMappings() + "extendshbm/entitynames.hbm.xml" );

		cfg.buildMappings();

		assertNotNull( cfg.getClassMapping( "EntityHasName" ) );
		assertNotNull( cfg.getClassMapping( "EntityCompany" ) );

	}
	catch ( HibernateException e ) {
		e.printStackTrace();
		fail( "should not fail with exception! " + e );

	}
}
 
Example #16
Source File: EagerKeyManyToOneTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void configure(Configuration cfg) {
	super.configure( cfg );
	cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
	LoadEventListener[] baseListeners = cfg.getEventListeners().getLoadEventListeners();
	int baseLength = baseListeners.length;
	LoadEventListener[] expandedListeners = new LoadEventListener[ baseLength + 1 ];
	expandedListeners[ 0 ] = new CustomLoadListener();
	System.arraycopy( baseListeners, 0, expandedListeners, 1, baseLength );
	cfg.getEventListeners().setLoadEventListeners( expandedListeners );
}
 
Example #17
Source File: HibernateUtil.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
private static SessionFactory buildSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration().configure();
    // configures settings from hibernate.cfg.xml

    StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();

    // If you miss the below line then it will complain about a missing dialect setting
    serviceRegistryBuilder.applySettings(configuration.getProperties());

    ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example #18
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Configuration newConfiguration() throws HibernateException {
	return new Configuration() {
		@Override
		public void addFilterDefinition(FilterDefinition definition) {
			registeredFilterDefinitions.add(definition);
		}
	};
}
 
Example #19
Source File: HibernateConfiguration.java    From elepy with Apache License 2.0 5 votes vote down vote up
static HibernateConfiguration createInMemoryHibernateConfig(String driverClassName, String url, String dialect, String username, String password) {
    Properties properties = new Properties();
    properties.setProperty("hibernate.connection.driver_class", driverClassName);
    properties.setProperty("hibernate.connection.url", url);
    properties.setProperty("hibernate.connection.username", username);
    properties.setProperty("hibernate.connection.password", password);
    properties.setProperty("hibernate.show_sql", "false");
    properties.setProperty("hibernate.dialect", dialect);
    properties.setProperty("hibernate.hbm2ddl.auto", "create");

    return HibernateConfiguration.of(new org.hibernate.cfg.Configuration().setProperties(properties));

}
 
Example #20
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithTransactionAwareDataSource() throws Exception {
	final DriverManagerDataSource ds = new DriverManagerDataSource();
	final List invocations = new ArrayList();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration addInputStream(InputStream is) {
					try {
						is.close();
					}
					catch (IOException ex) {
					}
					invocations.add("addResource");
					return this;
				}
			};
		}

		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(TransactionAwareDataSourceConnectionProvider.class.getName(),
					config.getProperty(Environment.CONNECTION_PROVIDER));
			assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
			invocations.add("newSessionFactory");
			return null;
		}
	};
	sfb.setDataSource(ds);
	sfb.setUseTransactionAwareDataSource(true);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertEquals("newSessionFactory", invocations.get(0));
}
 
Example #21
Source File: IterateTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void configure(Configuration cfg) {
	super.configure( cfg );
	cfg.setProperty( Environment.USE_QUERY_CACHE, "true" );
	cfg.setProperty( Environment.CACHE_REGION_PREFIX, "foo" );
	cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" );
	cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
}
 
Example #22
Source File: SubselectFetchTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Node.class );
	configuration.addAnnotatedClass( Element.class );
	return configuration;
}
 
Example #23
Source File: CreateTestInitializeDataBaseSqlFile.java    From base-framework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	
	Configuration configuration = new Configuration().configure().setNamingStrategy(new ImprovedNamingStrategy());
	EnversSchemaGenerator generator = new EnversSchemaGenerator(configuration);
	SchemaExport export = generator.export();
	
	export.setFormat(false);
	export.setOutputFile("src/test/resources/h2schma.sql");
	export.create(true, false);
}
 
Example #24
Source File: CacheHibernateStoreSessionListener.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override public void start() throws IgniteException {
    if (sesFactory == null && F.isEmpty(hibernateCfgPath)) {
        throw new IgniteException("Either session factory or Hibernate configuration file is required by " +
            getClass().getSimpleName() + '.');
    }

    if (!F.isEmpty(hibernateCfgPath)) {
        if (sesFactory == null) {
            try {
                URL url = new URL(hibernateCfgPath);

                sesFactory = new Configuration().configure(url).buildSessionFactory();
            }
            catch (MalformedURLException ex) {
                log.warning("Exception on store listener start", ex);
            }

            if (sesFactory == null) {
                File cfgFile = new File(hibernateCfgPath);

                if (cfgFile.exists())
                    sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();
            }

            if (sesFactory == null)
                sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

            if (sesFactory == null)
                throw new IgniteException("Failed to resolve Hibernate configuration file: " + hibernateCfgPath);

            closeSesOnStop = true;
        }
        else {
            U.warn(log, "Hibernate configuration file configured in " + getClass().getSimpleName() +
                " will be ignored (session factory is already set).");
        }
    }
}
 
Example #25
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception {
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration setInterceptor(Interceptor interceptor) {
					throw new IllegalArgumentException(interceptor.toString());
				}
			};
		}
	};
	sfb.setMappingResources(new String[0]);
	sfb.setDataSource(new DriverManagerDataSource());
	Interceptor entityInterceptor = mock(Interceptor.class);
	sfb.setEntityInterceptor(entityInterceptor);
	try {
		sfb.afterPropertiesSet();
		fail("Should have thrown IllegalArgumentException");
	}
	catch (IllegalArgumentException ex) {
		// expected
		assertTrue("Correct exception", ex.getMessage().equals(entityInterceptor.toString()));
	}
}
 
Example #26
Source File: ExternalSessionFactoryConfig.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected final Configuration buildConfiguration() {

		Configuration cfg = new Configuration().setProperties( buildProperties() );


		String[] mappingFiles = PropertiesHelper.toStringArray( mapResources, " ,\n\t\r\f" );
		for ( int i = 0; i < mappingFiles.length; i++ ) {
			cfg.addResource( mappingFiles[i] );
		}

		if ( customListeners != null && !customListeners.isEmpty() ) {
			Iterator entries = customListeners.entrySet().iterator();
			while ( entries.hasNext() ) {
				final Map.Entry entry = ( Map.Entry ) entries.next();
				final String type = ( String ) entry.getKey();
				final Object value = entry.getValue();
				if ( value != null ) {
					if ( String.class.isAssignableFrom( value.getClass() ) ) {
						// Its the listener class name
						cfg.setListener( type, ( ( String ) value ) );
					}
					else {
						// Its the listener instance (or better be)
						cfg.setListener( type, value );
					}
				}
			}
		}

		return cfg;
	}
 
Example #27
Source File: BatchFetchTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Node.class );
	configuration.addAnnotatedClass( Element.class );
	return configuration;
}
 
Example #28
Source File: AbstractUserTypeHibernateIntegrator.java    From jadira with Apache License 2.0 5 votes vote down vote up
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
    
	try {
		ConfigurationHelper.setCurrentSessionFactory(sessionFactory);
	
		String isEnabled = configuration.getProperty(REGISTER_USERTYPES_KEY); 
		String javaZone = configuration.getProperty(DEFAULT_JAVAZONE_KEY);
		String databaseZone = configuration.getProperty(DEFAULT_DATABASEZONE_KEY);
		String seed = configuration.getProperty(DEFAULT_SEED_KEY);
		String currencyCode = configuration.getProperty(DEFAULT_CURRENCYCODE_KEY);
		
		String jdbc42Apis = configuration.getProperty(JDBC42_API_KEY);
		
		configureDefaultProperties(sessionFactory, javaZone, databaseZone, seed, currencyCode, jdbc42Apis);
	
		if (isEnabled != null && Boolean.valueOf(isEnabled)) {
			autoRegisterUsertypes(configuration);
		}
		
		final boolean use42Api = use42Api(configuration.getProperty(JDBC42_API_KEY), sessionFactory);
		ConfigurationHelper.setUse42Api(sessionFactory, use42Api);
		
		// doIntegrate(configuration, sessionFactory, serviceRegistry);
	} finally {
		ConfigurationHelper.setCurrentSessionFactory(null);
	}
}
 
Example #29
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception {
	final DriverManagerDataSource ds = new DriverManagerDataSource();
	final Set invocations = new HashSet();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration addJar(File file) {
					invocations.add("addResource " + file.getPath());
					return this;
				}
			};
		}

		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(LocalDataSourceConnectionProvider.class.getName(),
					config.getProperty(Environment.CONNECTION_PROVIDER));
			assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
			invocations.add("newSessionFactory");
			return null;
		}
	};
	sfb.setMappingJarLocations(new Resource[]{
			new FileSystemResource("mapping.hbm.jar"), new FileSystemResource("mapping2.hbm.jar")});
	sfb.setDataSource(ds);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertTrue(invocations.contains("addResource mapping.hbm.jar"));
	assertTrue(invocations.contains("addResource mapping2.hbm.jar"));
	assertTrue(invocations.contains("newSessionFactory"));
}
 
Example #30
Source File: CollectionTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(Configuration cfg) {
    super.configure(cfg);
    cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName());
    cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;");
    cfg.setProperty(Environment.USER, "sa");
    cfg.setProperty(Environment.PASS, "");
    cfg.setProperty(Environment.CACHE_REGION_PREFIX, "");
    cfg.setProperty(Environment.GENERATE_STATISTICS, "true");

    cfg.setProperty(Environment.SHOW_SQL, "true");
    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
    cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName());
}