Java Code Examples for org.hibernate.cfg.Configuration#addResource()

The following examples show how to use org.hibernate.cfg.Configuration#addResource() . 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: 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 2
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 3
Source File: ExtendsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testOutOfOrder() {
	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/Person.hbm.xml" );
		cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" );

		cfg.buildSessionFactory();

		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Employee" ) );

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

}
 
Example 4
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 5
Source File: ExtendsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testUnionSubclass() {
	Configuration cfg = new Configuration();

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

		cfg.buildMappings();

		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) );

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

	}
}
 
Example 6
Source File: AbstractExecutable.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public final void prepare() {
	Configuration cfg = new Configuration().setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
	String[] resources = getResources();
	for ( int i = 0; i < resources.length; i++ ) {
		cfg.addResource( resources[i] );
	}
	factory = cfg.buildSessionFactory();
}
 
Example 7
Source File: ExtendsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testNwaitingForSuper() {
	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" );
		assertNull(
				"cannot be in the configuration yet!",
				cfg.getClassMapping( "org.hibernate.test.extendshbm.Employee" )
		);
		cfg.addResource( getBaseForMappings() + "extendshbm/Person.hbm.xml" );

		cfg.buildMappings();

		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Employee" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) );


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

	}

}
 
Example 8
Source File: EntityResolverTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testEntityIncludeResolution() {
	// Parent.hbm.xml contains the following entity include:
	//		<!ENTITY child SYSTEM "classpath://org/hibernate/test/util/dtd/child.xml">
	// which we are expecting the Hibernate custom entity resolver to be able to resolve
	// locally via classpath lookup.
	Configuration cfg = new Configuration();
	cfg.addResource( "org/hibernate/test/util/dtd/Parent.hbm.xml" );
	cfg.buildMappings();
}
 
Example 9
Source File: MappingExceptionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testDuplicateMapping() {
	String resourceName = "org/hibernate/test/mappingexception/User.hbm.xml";
	Configuration cfg = new Configuration();
	cfg.addResource( resourceName );
	try {
		cfg.addResource( resourceName );
		fail();
	}
	catch ( InvalidMappingException inv ) {
		assertEquals( inv.getType(), "resource" );
		assertEquals( inv.getPath(), resourceName );
		assertClassAssignability( inv.getCause().getClass(), DuplicateMappingException.class );
	}
}
 
Example 10
Source File: TestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void addMappings(String[] files, Configuration cfg) {
	for ( int i = 0; i < files.length; i++ ) {
		if ( !files[i].startsWith( "net/" ) ) {
			files[i] = getBaseForMappings() + files[i];
		}
		cfg.addResource( files[i], TestCase.class.getClassLoader() );
	}
}
 
Example 11
Source File: BaseCoreFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void addMappings(Configuration configuration) {
  String[] mappings = getMappings();
  if ( mappings != null ) {
    for ( String mapping : mappings ) {
      configuration.addResource(
          getBaseForMappings() + mapping,
          getClass().getClassLoader()
      );
    }
  }
  Class<?>[] annotatedClasses = getAnnotatedClasses();
  if ( annotatedClasses != null ) {
    for ( Class<?> annotatedClass : annotatedClasses ) {
      configuration.addAnnotatedClass( annotatedClass );
    }
  }
  String[] annotatedPackages = getAnnotatedPackages();
  if ( annotatedPackages != null ) {
    for ( String annotatedPackage : annotatedPackages ) {
      configuration.addPackage( annotatedPackage );
    }
  }
  String[] xmlFiles = getXmlFiles();
  if ( xmlFiles != null ) {
    for ( String xmlFile : xmlFiles ) {
      try ( InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ) ) {
        configuration.addInputStream( is );
      }
      catch (IOException e) {
        throw new IllegalArgumentException( e );
      }
    }
  }
}
 
Example 12
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 13
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
private SessionFactory newSessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }
    configuration.setProperties(properties);
    return configuration.buildSessionFactory(
            new BootstrapServiceRegistryBuilder()
                    .build()
    );
}
 
Example 14
Source File: HibernateFabric.java    From r-course with MIT License 5 votes vote down vote up
/**
 * Configuration of session factory with Fabric integration.
 */
public static SessionFactory createSessionFactory(String fabricUrl, String username, String password, String fabricUser, String fabricPassword)
        throws Exception {
    // creating this here allows passing needed params to the constructor
    FabricMultiTenantConnectionProvider connProvider = new FabricMultiTenantConnectionProvider(fabricUrl, "employees", "employees", username, password,
            fabricUser, fabricPassword);
    ServiceRegistryBuilder srb = new ServiceRegistryBuilder();
    srb.addService(org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider.class, connProvider);
    srb.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

    Configuration config = new Configuration();
    config.setProperty("hibernate.multiTenancy", "DATABASE");
    config.addResource("com/mysql/fabric/demo/employee.hbm.xml");
    return config.buildSessionFactory(srb.buildServiceRegistry());
}
 
Example 15
Source File: ExecutionEnvironment.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void applyMappings(Configuration configuration) {
	String[] mappings = settings.getMappings();
	for ( int i = 0; i < mappings.length; i++ ) {
		configuration.addResource( settings.getBaseForMappings() + mappings[i], ExecutionEnvironment.class.getClassLoader() );
	}
}
 
Example 16
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor(new TypeContributor() {
            @Override
            public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
                for (Type type : additionalTypes) {
                    if (type instanceof BasicType) {
                        typeContributions.contributeType((BasicType) type);
                    } else if (type instanceof UserType) {
                        typeContributions.contributeType((UserType) type);
                    } else if (type instanceof CompositeUserType) {
                        typeContributions.contributeType((CompositeUserType) type);
                    }
                }
            }
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 17
Source File: ConnectionManager.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a SessionFactory, loading the hbm.xml files from the specified
 * location.
 * @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);
    }
}
 
Example 18
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for(Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if(packages != null) {
        for(String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if(interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor((typeContributions, serviceRegistry) -> {
            additionalTypes.stream().forEach(type -> {
                if(type instanceof BasicType) {
                    typeContributions.contributeType((BasicType) type);
                } else if (type instanceof UserType ){
                    typeContributions.contributeType((UserType) type);
                } else if (type instanceof CompositeUserType) {
                    typeContributions.contributeType((CompositeUserType) type);
                }
            });
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 19
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor((typeContributions, serviceRegistry) -> {
            additionalTypes.stream().forEach(type -> {
                if (type instanceof BasicType) {
                    typeContributions.contributeType((BasicType) type);
                } else if (type instanceof UserType) {
                    typeContributions.contributeType((UserType) type);
                } else if (type instanceof CompositeUserType) {
                    typeContributions.contributeType((CompositeUserType) type);
                }
            });
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 20
Source File: ConnectionManager.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a SessionFactory, loading the hbm.xml files from the specified
 * location.
 * @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);

        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);
            }
        }

        //TODO: Fix auto-discovery (see commit: e92b062)
        AnnotationRegistry.getAnnotationClasses().forEach(c -> {
            config.addAnnotatedClass(c);
        });

        // 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);
    }
}