Allow a fine tuned configuration of an EJB 3.0 EntityManagerFactory
A Ejb3Configuration object is only guaranteed to create one EntityManagerFactory.
Multiple usage of #buildEntityManagerFactory() is not guaranteed.
After #buildEntityManagerFactory() has been called, you no longer can change the configuration
state (no class adding, no property change etc)
When serialized / deserialized or retrieved from the JNDI, you no longer can change the
configuration state (no class adding, no property change etc)
Putting the configuration in the JNDI is an expensive operation that requires a partial
serialization
| Method from org.hibernate.ejb.Ejb3Configuration Detail: |
public Ejb3Configuration addAnnotatedClass(Class persistentClass) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addAnnotatedClass( persistentClass );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public void addAuxiliaryDatabaseObject(AuxiliaryDatabaseObject object) {
cfg.addAuxiliaryDatabaseObject( object );
}
|
public Ejb3Configuration addClass(Class persistentClass) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addClass( persistentClass );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration addFile(String xmlFile) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addFile( xmlFile );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration addFile(File xmlFile) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addFile( xmlFile );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public void addFilterDefinition(FilterDefinition definition) {
cfg.addFilterDefinition( definition );
}
|
public Ejb3Configuration addInputStream(InputStream xmlInputStream) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addInputStream( xmlInputStream );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration addPackage(String packageName) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addPackage( packageName );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration addProperties(Properties props) {
cfg.addProperties( props );
return this;
}
|
public Ejb3Configuration addResource(String path) throws MappingException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.addResource( path );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration addResource(String path,
ClassLoader classLoader) throws MappingException {
cfg.addResource( path, classLoader );
return this;
}
|
public EntityManagerFactory buildEntityManagerFactory() {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
configure( (Properties)null, null );
NamingHelper.bind(this);
return new EntityManagerFactoryImpl(
cfg.buildSessionFactory(),
transactionType,
discardOnClose
);
}
catch (HibernateException e) {
throw new PersistenceException( e );
}
finally {
if (thread != null) {
thread.setContextClassLoader( contextClassLoader );
}
}
}
|
public void buildMappings() {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
cfg.buildMappings();
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
SessionFactory buildSessionFactory() throws HibernateException {
return cfg.buildSessionFactory();
}
|
public Settings buildSettings() throws HibernateException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
return settingsFactory.buildSettings( cfg.getProperties() );
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration configure(String resource) throws HibernateException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
Properties properties = new Properties();
properties.setProperty( HibernatePersistence.CFG_FILE, resource);
configure( properties, new HashMap() );
return this;
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Ejb3Configuration configure(String persistenceUnitName,
Map integration) {
try {
log.debug( "Look up for persistence unit: " + persistenceUnitName );
integration = integration == null ?
CollectionHelper.EMPTY_MAP :
Collections.unmodifiableMap( integration );
Enumeration< URL > xmls = Thread.currentThread()
.getContextClassLoader()
.getResources( "META-INF/persistence.xml" );
if ( ! xmls.hasMoreElements() ) {
log.info( "Could not find any META-INF/persistence.xml file in the classpath");
}
while ( xmls.hasMoreElements() ) {
URL url = xmls.nextElement();
log.trace( "Analyse of persistence.xml: " + url );
List< PersistenceMetadata > metadataFiles = PersistenceXmlLoader.deploy(
url,
integration,
cfg.getEntityResolver(),
PersistenceUnitTransactionType.RESOURCE_LOCAL );
for ( PersistenceMetadata metadata : metadataFiles ) {
log.trace( metadata.toString() );
if ( metadata.getProvider() == null || IMPLEMENTATION_NAME.equalsIgnoreCase(
metadata.getProvider()
) ) {
//correct provider
//lazy compute the visitor if possible to avoid useless exceptions if an unexpected state happens
JarVisitor visitor = null;
if ( metadata.getName() == null ) {
visitor = getMainJarVisitor( url, metadata, integration );
metadata.setName( visitor.getUnqualifiedJarName() );
}
if ( persistenceUnitName == null && xmls.hasMoreElements() ) {
throw new PersistenceException( "No name provided and several persistence units found" );
}
else if ( persistenceUnitName == null || metadata.getName().equals( persistenceUnitName ) ) {
if (visitor == null) visitor = getMainJarVisitor( url, metadata, integration );
addMetadataFromVisitor( visitor, metadata );
JarVisitor.Filter[] otherXmlFilter = getFilters( metadata, integration, false );
for ( String jarFile : metadata.getJarFiles() ) {
visitor = JarVisitor.getVisitor( jarFile, otherXmlFilter );
addMetadataFromVisitor( visitor, metadata );
}
return configure( metadata, integration );
}
}
}
}
return null;
}
catch (Exception e) {
if ( e instanceof PersistenceException) {
throw (PersistenceException) e;
}
else {
throw new PersistenceException( e );
}
}
}
Build the configuration from an entity manager name and given the
appropriate extra properties. Those properties override the one get through
the peristence.xml file.
If the persistence unit name is not found or does not match the Persistence Provider, null is returned |
public Ejb3Configuration configure(PersistenceUnitInfo info,
Map integration) {
if ( log.isDebugEnabled() ) {
log.debug( "Processing " + LogHelper.logPersistenceUnitInfo( info ) );
}
else {
log.info( "Processing PersistenceUnitInfo [\n\tname: " + info.getPersistenceUnitName() + "\n\t...]" );
}
integration = integration != null ? Collections.unmodifiableMap( integration ) : CollectionHelper.EMPTY_MAP;
String provider = (String) integration.get( HibernatePersistence.PROVIDER );
if ( provider == null ) provider = info.getPersistenceProviderClassName();
if ( provider != null && ! provider.trim().startsWith( IMPLEMENTATION_NAME ) ) {
log.info( "Required a different provider: " + provider );
return null;
}
if ( info.getClassLoader() == null ) {
throw new IllegalStateException(
"[PersistenceUnit: " + info.getPersistenceUnitName() == null ? "" : info.getPersistenceUnitName()
+ "] " + "PersistenceUnitInfo.getClassLoader() id null" );
}
//set the classloader
Thread thread = Thread.currentThread();
ClassLoader contextClassLoader = thread.getContextClassLoader();
boolean sameClassLoader = info.getClassLoader().equals( contextClassLoader );
if ( ! sameClassLoader ) {
overridenClassLoader = info.getClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
else {
overridenClassLoader = null;
}
try {
Map workingVars = new HashMap();
workingVars.put( HibernatePersistence.PERSISTENCE_UNIT_NAME, info.getPersistenceUnitName() );
List< String > entities = new ArrayList< String >( 50 );
if ( info.getManagedClassNames() != null ) entities.addAll( info.getManagedClassNames() );
List< NamedInputStream > hbmFiles = new ArrayList< NamedInputStream >();
List< String > packages = new ArrayList< String >();
List< String > xmlFiles = new ArrayList< String >( 50 );
if ( info.getMappingFileNames() != null ) xmlFiles.addAll( info.getMappingFileNames() );
//Should always be true if the container is not dump
boolean searchForORMFiles = ! xmlFiles.contains( META_INF_ORM_XML );
boolean[] detectArtifactForOtherJars = getDetectedArtifacts( info.getProperties(), null, false );
boolean[] detectArtifactForMainJar = getDetectedArtifacts( info.getProperties(), null, info.excludeUnlistedClasses() );
for ( URL jar : info.getJarFileUrls() ) {
if ( detectArtifactForOtherJars[0] ) scanForClasses( jar, packages, entities );
if ( detectArtifactForOtherJars[1] ) scanForXmlFiles( jar, hbmFiles, searchForORMFiles );
}
if ( detectArtifactForMainJar[0] ) scanForClasses( info.getPersistenceUnitRootUrl(), packages, entities );
if ( detectArtifactForMainJar[1] )
scanForXmlFiles( info.getPersistenceUnitRootUrl(), hbmFiles, searchForORMFiles );
Properties properties = info.getProperties() != null ?
info.getProperties() :
new Properties();
ConfigurationHelper.overrideProperties( properties, integration );
//FIXME entities is used to enhance classes and to collect annotated entities this should not be mixed
//fill up entities with the on found in xml files
addXMLEntities( xmlFiles, info, entities );
//FIXME send the appropriate entites.
if ( "true".equalsIgnoreCase( properties.getProperty( HibernatePersistence.USE_CLASS_ENHANCER ) ) ) {
info.addTransformer( new InterceptFieldClassFileTransformer( entities ) );
}
workingVars.put( HibernatePersistence.CLASS_NAMES, entities );
workingVars.put( HibernatePersistence.PACKAGE_NAMES, packages );
workingVars.put( HibernatePersistence.XML_FILE_NAMES, xmlFiles );
if ( hbmFiles.size() > 0 ) workingVars.put( HibernatePersistence.HBXML_FILES, hbmFiles );
//datasources
Boolean isJTA = null;
boolean overridenDatasource = false;
if ( integration.containsKey( HibernatePersistence.JTA_DATASOURCE ) ) {
String dataSource = (String) integration.get( HibernatePersistence.JTA_DATASOURCE );
overridenDatasource = true;
properties.setProperty( Environment.DATASOURCE, dataSource );
isJTA = Boolean.TRUE;
}
if ( integration.containsKey( HibernatePersistence.NON_JTA_DATASOURCE ) ) {
String dataSource = (String) integration.get( HibernatePersistence.NON_JTA_DATASOURCE );
overridenDatasource = true;
properties.setProperty( Environment.DATASOURCE, dataSource );
if (isJTA == null) isJTA = Boolean.FALSE;
}
if ( ! overridenDatasource && ( info.getJtaDataSource() != null || info.getNonJtaDataSource() != null ) ) {
isJTA = info.getJtaDataSource() != null ? Boolean.TRUE : Boolean.FALSE;
this.setDataSource(
isJTA ? info.getJtaDataSource() : info.getNonJtaDataSource()
);
this.setProperty(
Environment.CONNECTION_PROVIDER, InjectedDataSourceConnectionProvider.class.getName()
);
}
/*
* If explicit type = > use it
* If a JTA DS is used = > JTA transaction,
* if a non JTA DS is used = > RESOURCe_LOCAL
* if none, set to JavaEE default = > JTA transaction
*/
PersistenceUnitTransactionType transactionType = info.getTransactionType();
if (transactionType == null) {
if (isJTA == Boolean.TRUE) {
transactionType = PersistenceUnitTransactionType.JTA;
}
else if ( isJTA == Boolean.FALSE ) {
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
else {
transactionType = PersistenceUnitTransactionType.JTA;
}
}
defineTransactionType( transactionType, workingVars );
configure( properties, workingVars );
}
finally {
//After EMF, set the CCL back
if ( ! sameClassLoader ) {
thread.setContextClassLoader( contextClassLoader );
}
}
return this;
}
Process configuration from a PersistenceUnitInfo object
Typically called by the container |
public EntityManagerFactory createEntityManagerFactory() {
configure( cfg.getProperties(), new HashMap() );
return buildEntityManagerFactory();
} Deprecated!
Process configuration and build an EntityManagerFactory when the configuration is ready |
public EntityManagerFactory createEntityManagerFactory(Map workingVars) {
Properties props = new Properties();
if ( workingVars != null ) {
props.putAll( workingVars );
//remove huge non String elements for a clean props
props.remove( HibernatePersistence.CLASS_NAMES );
props.remove( HibernatePersistence.PACKAGE_NAMES );
props.remove( HibernatePersistence.HBXML_FILES );
props.remove( HibernatePersistence.LOADED_CLASSES );
}
configure( props, workingVars );
return buildEntityManagerFactory();
} Deprecated! use - the Java Persistence API
create a factory from a list of properties and
HibernatePersistence.CLASS_NAMES -> Collection (use to list the classes from config files
HibernatePersistence.PACKAGE_NAMES -> Collection (use to list the mappings from config files
HibernatePersistence.HBXML_FILES -> Collection (input streams of hbm files)
HibernatePersistence.LOADED_CLASSES -> Collection (list of loaded classes)
Used by JBoss AS only |
public PersistentClass getClassMapping(String persistentClass) {
return cfg.getClassMapping( persistentClass );
}
|
public Iterator getClassMappings() {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
thread = Thread.currentThread();
contextClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader( overridenClassLoader );
}
try {
return cfg.getClassMappings();
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
|
public Collection getCollectionMapping(String role) {
return cfg.getCollectionMapping( role );
}
|
public EventListeners getEventListeners() {
return cfg.getEventListeners();
}
|
public Map getFilterDefinitions() {
return cfg.getFilterDefinitions();
}
|
public AnnotationConfiguration getHibernateConfiguration() {
//TODO make it really read only (maybe through proxying)
return cfg;
}
This API is intended to give a read-only configuration.
It is sueful when working with SchemaExport or any Configuration based
tool.
DO NOT update configuration through it. |
public Interceptor getInterceptor() {
return cfg.getInterceptor();
}
|
public Map getNamedQueries() {
return cfg.getNamedQueries();
}
|
public NamingStrategy getNamingStrategy() {
return cfg.getNamingStrategy();
}
|
public Properties getProperties() {
return cfg.getProperties();
}
|
public Reference getReference() throws NamingException {
log.debug("Returning a Reference to the Ejb3Configuration");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = null;
byte[] serialized;
try {
out = new ObjectOutputStream( stream );
out.writeObject( this );
out.close();
serialized = stream.toByteArray();
stream.close();
}
catch (IOException e) {
NamingException namingException = new NamingException( "Unable to serialize Ejb3Configuration" );
namingException.setRootCause( e );
throw namingException;
}
return new Reference(
Ejb3Configuration.class.getName(),
new BinaryRefAddr("object", serialized ),
Ejb3ConfigurationObjectFactory.class.getName(),
null
);
}
|
public Iterator getTableMappings() {
return cfg.getTableMappings();
}
|
public void setDataSource(DataSource ds) {
if ( ds != null ) {
Map cpInjection = new HashMap();
cpInjection.put( "dataSource", ds );
( (InjectionSettingsFactory) settingsFactory ).setConnectionProviderInjectionData( cpInjection );
this.setProperty( Environment.CONNECTION_PROVIDER, InjectedDataSourceConnectionProvider.class.getName() );
}
}
Used to inject a datasource object as the connection provider.
If used, be sure to not override the hibernate.connection.provider_class
property |
public void setEntityResolver(EntityResolver entityResolver) {
cfg.setEntityResolver( entityResolver );
}
|
public Ejb3Configuration setInterceptor(Interceptor interceptor) {
cfg.setInterceptor( interceptor );
return this;
}
|
public void setListeners(String type,
String[] listenerClasses) {
cfg.setListeners( type, listenerClasses );
}
|
public void setListeners(String type,
Object[] listeners) {
cfg.setListeners( type, listeners );
}
|
public Ejb3Configuration setNamingStrategy(NamingStrategy namingStrategy) {
cfg.setNamingStrategy( namingStrategy );
return this;
}
|
public Ejb3Configuration setProperties(Properties properties) {
cfg.setProperties( properties );
return this;
}
|
public Ejb3Configuration setProperty(String key,
String value) {
cfg.setProperty( key, value );
return this;
}
|