下面列出了org.hibernate.cfg.Configuration#addResource ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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 );
}
}
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() );
}
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 );
}
}
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 ) {
}
}
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 );
}
}
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 );
}
}
}
}
/**
* 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());
}
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()
);
}
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;
}
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();
}
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() );
}
}
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 );
}
}
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();
}
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 );
}
}
/**
* 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);
}
}
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()
);
}
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()
);
}
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()
);
}
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() );
}
}
/**
* 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);
}
}