HHH-6110 : Integrate new metamodel into persisters

This commit is contained in:
Gail Badner 2011-06-06 17:26:37 -07:00
parent 9c90c25fea
commit ba44ae26cb
16 changed files with 660 additions and 46 deletions

View File

@ -32,6 +32,7 @@
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.stat.Statistics;
/**
@ -51,6 +52,14 @@
* @author Steve Ebersole
*/
public interface SessionFactory extends Referenceable, Serializable {
public interface SessionFactoryOptions {
Interceptor getInterceptor();
EntityNotFoundDelegate getEntityNotFoundDelegate();
}
public SessionFactoryOptions getSessionFactoryOptions();
/**
* Obtain a {@link Session} builder.
*

View File

@ -28,6 +28,7 @@
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.type.VersionType;
/**
@ -66,6 +67,24 @@ public static CacheDataDescriptionImpl decode(PersistentClass model) {
);
}
public static CacheDataDescriptionImpl decode(EntityBinding model) {
Comparator versionComparator = null;
if ( model.isVersioned() ) {
versionComparator = (
( VersionType ) model
.getVersioningValueBinding()
.getHibernateTypeDescriptor()
.getExplicitType()
).getComparator();
}
return new CacheDataDescriptionImpl(
model.isMutable(),
model.isVersioned(),
versionComparator
);
}
public static CacheDataDescriptionImpl decode(Collection model) {
return new CacheDataDescriptionImpl(
model.isMutable(),

View File

@ -61,7 +61,7 @@ public class SettingsFactory implements Serializable {
public static final String DEF_CACHE_REG_FACTORY = NoCachingRegionFactory.class.getName();
protected SettingsFactory() {
public SettingsFactory() {
}
public Settings buildSettings(Properties props, ServiceRegistry serviceRegistry) {

View File

@ -75,10 +75,10 @@
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy;
import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.Settings;
import org.hibernate.cfg.SettingsFactory;
import org.hibernate.context.internal.ThreadLocalSessionContext;
import org.hibernate.context.spi.CurrentSessionContext;
import org.hibernate.context.internal.JTASessionContext;
@ -186,7 +186,6 @@ public final class SessionFactoryImpl
private final transient Map<String, FilterDefinition> filters;
private final transient Map fetchProfiles;
private final transient Map imports;
private final transient Interceptor interceptor;
private final transient SessionFactoryServiceRegistry serviceRegistry;
private final transient Settings settings;
private final transient Properties properties;
@ -196,7 +195,6 @@ public final class SessionFactoryImpl
private final transient Map<String,QueryCache> queryCaches;
private final transient ConcurrentMap<String,Region> allCacheRegions = new ConcurrentHashMap<String, Region>();
private final transient CurrentSessionContext currentSessionContext;
private final transient EntityNotFoundDelegate entityNotFoundDelegate;
private final transient SQLFunctionRegistry sqlFunctionRegistry;
private final transient SessionFactoryObserverChain observer = new SessionFactoryObserverChain();
private final transient HashMap entityNameResolvers = new HashMap();
@ -206,18 +204,44 @@ public final class SessionFactoryImpl
private final transient TypeResolver typeResolver;
private final transient TypeHelper typeHelper;
private final transient TransactionEnvironment transactionEnvironment;
private final transient SessionFactoryOptions sessionFactoryOptions;
@SuppressWarnings( {"unchecked"} )
public SessionFactoryImpl(
Configuration cfg,
final Configuration cfg,
Mapping mapping,
ServiceRegistry serviceRegistry,
Settings settings,
SessionFactoryObserver observer) throws HibernateException {
LOG.debug( "Building session factory" );
sessionFactoryOptions = new SessionFactoryOptions() {
private EntityNotFoundDelegate entityNotFoundDelegate;
@Override
public Interceptor getInterceptor() {
return cfg.getInterceptor();
}
@Override
public EntityNotFoundDelegate getEntityNotFoundDelegate() {
if ( entityNotFoundDelegate == null ) {
if ( cfg.getEntityNotFoundDelegate() != null ) {
entityNotFoundDelegate = cfg.getEntityNotFoundDelegate();
}
else {
entityNotFoundDelegate = new EntityNotFoundDelegate() {
public void handleEntityNotFound(String entityName, Serializable id) {
throw new ObjectNotFoundException( id, entityName );
}
};
}
}
return entityNotFoundDelegate;
}
};
this.settings = settings;
this.interceptor = cfg.getInterceptor();
this.properties = new Properties();
this.properties.putAll( cfg.getProperties() );
@ -455,17 +479,6 @@ public void sessionFactoryClosed(SessionFactory factory) {
}
}
// EntityNotFoundDelegate
EntityNotFoundDelegate entityNotFoundDelegate = cfg.getEntityNotFoundDelegate();
if ( entityNotFoundDelegate == null ) {
entityNotFoundDelegate = new EntityNotFoundDelegate() {
public void handleEntityNotFound(String entityName, Serializable id) {
throw new ObjectNotFoundException( id, entityName );
}
};
}
this.entityNotFoundDelegate = entityNotFoundDelegate;
// this needs to happen after persisters are all ready to go...
this.fetchProfiles = new HashMap();
itr = cfg.iterateFetchProfiles();
@ -509,52 +522,48 @@ public void handleEntityNotFound(String entityName, Serializable id) {
public SessionFactoryImpl(
MetadataImplementor metadata,
Mapping mapping,
ServiceRegistry serviceRegistry,
SessionFactoryOptions sessionFactoryOptions,
SessionFactoryObserver observer) throws HibernateException {
LOG.debug( "Building session factory" );
// TODO: remove initialization of final variables; just setting to null to make compiler happy
this.name = null;
this.uuid = null;
this.entityPersisters = null;
this.classMetadata = null;
this.collectionPersisters = null;
this.collectionMetadata = null;
this.collectionRolesByEntityParticipant = null;
this.identifierGenerators = null;
this.namedQueries = null;
this.namedSqlQueries = null;
this.sqlResultSetMappings = null;
this.fetchProfiles = null;
this.imports = null;
this.interceptor = null;
this.queryCache = null;
this.updateTimestampsCache = null;
this.queryCaches = null;
this.currentSessionContext = null;
this.entityNotFoundDelegate = null;
this.sqlFunctionRegistry = null;
this.queryPlanCache = null;
this.transactionEnvironment = null;
ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
this.settings = null;
this.sessionFactoryOptions = sessionFactoryOptions;
this.serviceRegistry = serviceRegistry.getService( SessionFactoryServiceRegistryFactory.class ).buildServiceRegistry(
this,
metadata
this.properties = createPropertiesFromMap(
metadata.getServiceRegistry().getService( ConfigurationService.class ).getSettings()
);
// TODO: get Interceptor from ConfurationService
//this.interceptor = cfg.getInterceptor();
// TODO: these should be moved into SessionFactoryOptions
this.settings = new SettingsFactory().buildSettings(
properties,
metadata.getServiceRegistry()
);
// TODO: find references to properties and make sure everything needed is available to services via
// ConfigurationService
this.properties = null;
this.serviceRegistry =
metadata.getServiceRegistry()
.getService( SessionFactoryServiceRegistryFactory.class )
.buildServiceRegistry( this, metadata );
// TODO: get SQL functions from a new service
// this.sqlFunctionRegistry = new SQLFunctionRegistry( getDialect(), cfg.getSqlFunctions() );
// TODO: should this be build along w/ metadata? seems like it should so app has more control over it...
//this.sqlFunctionRegistry = new SQLFunctionRegistry( getDialect(), metadata.getSqlFunctions() );
if ( observer != null ) {
this.observer.addObserver( observer );
}
@ -568,10 +577,107 @@ public SessionFactoryImpl(
}
LOG.debugf("Session factory constructed with filter configurations : %s", filters);
LOG.debugf("Instantiating session factory with properties: %s", configurationService.getSettings() );
LOG.debugf("Instantiating session factory with properties: %s", properties );
// TODO: get RegionFactory from service registry
settings.getRegionFactory().start( settings, properties );
this.queryPlanCache = new QueryPlanCache( this );
class IntegratorObserver implements SessionFactoryObserver {
private ArrayList<Integrator> integrators = new ArrayList<Integrator>();
@Override
public void sessionFactoryCreated(SessionFactory factory) {
}
@Override
public void sessionFactoryClosed(SessionFactory factory) {
for ( Integrator integrator : integrators ) {
integrator.disintegrate( SessionFactoryImpl.this, SessionFactoryImpl.this.serviceRegistry );
}
}
}
final IntegratorObserver integratorObserver = new IntegratorObserver();
this.observer.addObserver( integratorObserver );
for ( Integrator integrator : serviceRegistry.getService( IntegratorService.class ).getIntegrators() ) {
// TODO: add Integrator.integrate(MetadataImplementor, ...)
// integrator.integrate( cfg, this, this.serviceRegistry );
integratorObserver.integrators.add( integrator );
}
//Generators:
identifierGenerators = new HashMap();
for ( EntityBinding entityBinding : metadata.getEntityBindings() ) {
if ( entityBinding.isRoot() ) {
// TODO: create the IdentifierGenerator while the metadata is being build, then simply
// use EntityBinding.getIdentifierGenerator() (also remove getIdentifierGeneratorFactory from Mappings)
IdentifierGenerator generator = entityBinding.getEntityIdentifier().createIdentifierGenerator(
metadata.getIdentifierGeneratorFactory()
);
identifierGenerators.put( entityBinding.getEntity().getName(), generator );
}
}
///////////////////////////////////////////////////////////////////////
// Prepare persisters and link them up with their cache
// region/access-strategy
StringBuilder stringBuilder = new StringBuilder();
if ( settings.getCacheRegionPrefix() != null) {
stringBuilder
.append( settings.getCacheRegionPrefix() )
.append( '.' );
}
final String cacheRegionPrefix = stringBuilder.toString();
entityPersisters = new HashMap();
Map<String, EntityRegionAccessStrategy> entityAccessStrategies = new HashMap<String, EntityRegionAccessStrategy>();
Map<String,ClassMetadata> classMeta = new HashMap<String,ClassMetadata>();
for ( EntityBinding model : metadata.getEntityBindings() ) {
// TODO: should temp table prep happen when metadata is being built?
//model.prepareTemporaryTables( metadata, getDialect() );
// cache region is defined by the root-class in the hierarchy...
EntityBinding rootEntityBinding = metadata.getRootEntityBinding( model.getEntity().getName() );
EntityRegionAccessStrategy accessStrategy = null;
if ( settings.isSecondLevelCacheEnabled() &&
rootEntityBinding.getCaching() != null &&
model.getCaching() != null &&
model.getCaching().getAccessType() != null ) {
final String cacheRegionName = cacheRegionPrefix + rootEntityBinding.getCaching().getRegion();
accessStrategy = entityAccessStrategies.get( cacheRegionName );
if ( accessStrategy == null ) {
final AccessType accessType = model.getCaching().getAccessType();
LOG.trace("Building cache for entity data [" + model.getEntity().getName() + "]");
EntityRegion entityRegion =
settings.getRegionFactory().buildEntityRegion(
cacheRegionName,
properties,
CacheDataDescriptionImpl.decode( model )
);
accessStrategy = entityRegion.buildAccessStrategy( accessType );
entityAccessStrategies.put( cacheRegionName, accessStrategy );
allCacheRegions.put( cacheRegionName, entityRegion );
}
}
EntityPersister cp = serviceRegistry.getService( PersisterFactory.class ).createEntityPersister(
model, accessStrategy, this, metadata
);
entityPersisters.put( model.getEntity().getName(), cp );
classMeta.put( model.getEntity().getName(), cp.getClassMetadata() );
}
this.classMetadata = Collections.unmodifiableMap(classMeta);
// TODO: implement
}
@SuppressWarnings( {"unchecked"} )
private static Properties createPropertiesFromMap(Map map) {
Properties properties = new Properties();
properties.putAll( map );
return properties;
}
public Session openSession() throws HibernateException {
@ -762,6 +868,11 @@ public Settings getSettings() {
return settings;
}
@Override
public SessionFactoryOptions getSessionFactoryOptions() {
return sessionFactoryOptions;
}
public JdbcServices getJdbcServices() {
return serviceRegistry.getService( JdbcServices.class );
}
@ -775,7 +886,7 @@ public Dialect getDialect() {
public Interceptor getInterceptor()
{
return interceptor;
return sessionFactoryOptions.getInterceptor();
}
public SQLExceptionConverter getSQLExceptionConverter() {
@ -1315,7 +1426,7 @@ public ServiceRegistryImplementor getServiceRegistry() {
@Override
public EntityNotFoundDelegate getEntityNotFoundDelegate() {
return entityNotFoundDelegate;
return sessionFactoryOptions.getEntityNotFoundDelegate();
}
public SQLFunctionRegistry getSqlFunctionRegistry() {

View File

@ -38,6 +38,8 @@
import org.hibernate.AssertionFailure;
import org.hibernate.Cache;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.StatelessSessionBuilder;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.Session;
@ -51,6 +53,7 @@
import org.hibernate.internal.SessionFactoryRegistry;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.jndi.internal.JndiServiceImpl;
import org.hibernate.stat.Statistics;
@ -88,6 +91,11 @@ public class SessionFactoryStub implements SessionFactory {
SessionFactoryRegistry.INSTANCE.addSessionFactory( uuid, name, this, new JndiServiceImpl( service.getProperties() ) );
}
@Override
public SessionFactoryOptions getSessionFactoryOptions() {
return impl.getSessionFactoryOptions();
}
@Override
public SessionBuilder withOptions() {
return getImpl().withOptions();

View File

@ -53,12 +53,21 @@ public static interface Options {
public Options getOptions();
public SessionFactoryBuilder getSessionFactoryBuilder();
public SessionFactory buildSessionFactory();
public Iterable<EntityBinding> getEntityBindings();
public EntityBinding getEntityBinding(String entityName);
/**
* Get the "root" entity binding
* @param entityName
* @return the "root entity binding; simply returns entityBinding if it is the root entity binding
*/
public EntityBinding getRootEntityBinding(String entityName);
public Iterable<TypeDef> getTypeDefinitions();
public Iterable<FilterDefinition> getFilterDefinitions();

View File

@ -0,0 +1,39 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel;
import org.hibernate.Interceptor;
import org.hibernate.SessionFactory;
import org.hibernate.proxy.EntityNotFoundDelegate;
/**
* @author Gail Badner
*/
public interface SessionFactoryBuilder {
public SessionFactoryBuilder with(Interceptor interceptor);
public SessionFactoryBuilder with(EntityNotFoundDelegate entityNotFoundDelegate);
public SessionFactory buildSessionFactory();
}

View File

@ -229,6 +229,10 @@ public InheritanceType getInheritanceType() {
return entityInheritanceType;
}
public boolean isVersioned() {
return versionBinding != null;
}
public SimpleAttributeBinding getVersioningValueBinding() {
return versionBinding;
}

View File

@ -33,15 +33,19 @@
import org.jboss.logging.Logger;
import org.hibernate.DuplicateMappingException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.id.factory.DefaultIdentifierGeneratorFactory;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.SourceProcessingOrder;
import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.metamodel.binding.IdGenerator;
@ -58,6 +62,7 @@
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import org.hibernate.service.BasicServiceRegistry;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
/**
@ -65,6 +70,7 @@
*
* @author Steve Ebersole
* @author Hardy Ferentschik
* @author Gail Badner
*/
public class MetadataImpl implements MetadataImplementor, Serializable {
@ -78,6 +84,9 @@ public class MetadataImpl implements MetadataImplementor, Serializable {
private ClassLoaderService classLoaderService;
private TypeResolver typeResolver = new TypeResolver();
private SessionFactoryBuilder sessionFactoryBuilder = new SessionFactoryBuilderImpl( this );
private DefaultIdentifierGeneratorFactory identifierGeneratorFactory = new DefaultIdentifierGeneratorFactory();
private final Database database = new Database();
@ -88,6 +97,7 @@ public class MetadataImpl implements MetadataImplementor, Serializable {
* Maps the fully qualified class name of an entity to its entity binding
*/
private Map<String, EntityBinding> entityBindingMap = new HashMap<String, EntityBinding>();
private Map<String, EntityBinding> rootEntityBindingMap = new HashMap<String, EntityBinding>();
private Map<String, PluralAttributeBinding> collectionBindingMap = new HashMap<String, PluralAttributeBinding>();
private Map<String, FetchProfile> fetchProfiles = new HashMap<String, FetchProfile>();
private Map<String, String> imports;
@ -253,8 +263,7 @@ public Options getOptions() {
@Override
public SessionFactory buildSessionFactory() {
// todo : implement!!!!
return null;
return sessionFactoryBuilder.buildSessionFactory();
}
@Override
@ -271,6 +280,28 @@ public EntityBinding getEntityBinding(String entityName) {
return entityBindingMap.get( entityName );
}
@Override
public EntityBinding getRootEntityBinding(String entityName) {
EntityBinding rootEntityBinding = rootEntityBindingMap.get( entityName );
if ( rootEntityBinding == null ) {
EntityBinding entityBinding = entityBindingMap.get( entityName );
if ( entityBinding == null ) {
throw new IllegalStateException( "Unknown entity binding: " + entityName );
}
if ( entityBinding.isRoot() ) {
rootEntityBinding = entityBinding;
}
else {
if ( entityBinding.getEntity().getSuperType() == null ) {
throw new IllegalStateException( "Entity binding has no root: " + entityName );
}
rootEntityBinding = getRootEntityBinding( entityBinding.getEntity().getSuperType().getName() );
}
rootEntityBindingMap.put( entityName, rootEntityBinding );
}
return rootEntityBinding;
}
public Iterable<EntityBinding> getEntityBindings() {
return entityBindingMap.values();
}
@ -320,6 +351,11 @@ public TypeResolver getTypeResolver() {
return typeResolver;
}
@Override
public SessionFactoryBuilder getSessionFactoryBuilder() {
return sessionFactoryBuilder;
}
@Override
public NamingStrategy getNamingStrategy() {
return options.getNamingStrategy();
@ -347,6 +383,48 @@ public MetadataImplementor getMetadataImplementor() {
private static final String DEFAULT_CASCADE = "none";
private static final String DEFAULT_PROPERTY_ACCESS = "property";
@Override
public IdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return identifierGeneratorFactory;
}
@Override
public Type getIdentifierType(String entityName) throws MappingException {
EntityBinding entityBinding = getEntityBinding( entityName );
if ( entityBinding == null ) {
throw new MappingException( "Entity binding not known: " + entityName );
}
return entityBinding
.getEntityIdentifier()
.getValueBinding()
.getHibernateTypeDescriptor()
.getExplicitType();
}
@Override
public String getIdentifierPropertyName(String entityName) throws MappingException {
EntityBinding entityBinding = getEntityBinding( entityName );
if ( entityBinding == null ) {
throw new MappingException( "Entity binding not known: " + entityName );
}
AttributeBinding idBinding = entityBinding.getEntityIdentifier().getValueBinding();
return idBinding == null ? null : idBinding.getAttribute().getName();
}
@Override
public Type getReferencedPropertyType(String entityName, String propertyName) throws MappingException {
EntityBinding entityBinding = getEntityBinding( entityName );
if ( entityBinding == null ) {
throw new MappingException( "Entity binding not known: " + entityName );
}
// TODO: should this call EntityBinding.getReferencedAttributeBindingString), which does not exist yet?
AttributeBinding attributeBinding = entityBinding.getAttributeBinding( propertyName );
if ( attributeBinding == null ) {
throw new MappingException( "unknown property: " + entityName + '.' + propertyName );
}
return attributeBinding.getHibernateTypeDescriptor().getExplicitType();
}
private class MappingDefaultsImpl implements MappingDefaults {
@Override

View File

@ -0,0 +1,88 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.internal;
import java.io.Serializable;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.SessionFactory;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import org.hibernate.proxy.EntityNotFoundDelegate;
/**
* @author Gail Badner
*/
public class SessionFactoryBuilderImpl implements SessionFactoryBuilder {
SessionFactoryOptionsImpl options;
private final MetadataImplementor metadata;
/* package-protected */
SessionFactoryBuilderImpl(MetadataImplementor metadata) {
this.metadata = metadata;
options = new SessionFactoryOptionsImpl();
}
@Override
public SessionFactoryBuilder with(Interceptor interceptor) {
this.options.interceptor = interceptor;
return this;
}
@Override
public SessionFactoryBuilder with(EntityNotFoundDelegate entityNotFoundDelegate) {
this.options.entityNotFoundDelegate = entityNotFoundDelegate;
return this;
}
@Override
public SessionFactory buildSessionFactory() {
return new SessionFactoryImpl(metadata, options, null );
}
private static class SessionFactoryOptionsImpl implements SessionFactory.SessionFactoryOptions {
private Interceptor interceptor = EmptyInterceptor.INSTANCE;
// TODO: should there be a DefaultEntityNotFoundDelegate.INSTANCE?
private EntityNotFoundDelegate entityNotFoundDelegate = new EntityNotFoundDelegate() {
public void handleEntityNotFound(String entityName, Serializable id) {
throw new ObjectNotFoundException( id, entityName );
}
};
@Override
public Interceptor getInterceptor() {
return interceptor;
}
@Override
public EntityNotFoundDelegate getEntityNotFoundDelegate() {
return entityNotFoundDelegate;
}
}
}

View File

@ -24,9 +24,11 @@
package org.hibernate.metamodel.source.spi;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.metamodel.Metadata;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.metamodel.binding.IdGenerator;
@ -40,7 +42,7 @@
/**
* @author Steve Ebersole
*/
public interface MetadataImplementor extends Metadata, BindingContext {
public interface MetadataImplementor extends Metadata, BindingContext, Mapping {
public BasicServiceRegistry getServiceRegistry();
public Database getDatabase();

View File

@ -33,6 +33,7 @@
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import org.hibernate.service.BasicServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.internal.BasicServiceRegistryImpl;
@ -74,6 +75,7 @@ protected BasicServiceRegistry basicServiceRegistry() {
public void testSimpleEntityMapping() {
MetadataImpl metadata = addSourcesForSimpleEntityBinding( sources );
EntityBinding entityBinding = metadata.getEntityBinding( SimpleEntity.class.getName() );
assertRoot( metadata, entityBinding );
assertIdAndSimpleProperty( entityBinding );
assertNull( entityBinding.getVersioningValueBinding() );
@ -123,7 +125,6 @@ protected void assertIdAndSimpleProperty(EntityBinding entityBinding) {
assertNotNull( entityBinding );
assertNotNull( entityBinding.getEntityIdentifier() );
assertNotNull( entityBinding.getEntityIdentifier().getValueBinding() );
assertTrue( entityBinding.isRoot() );
AttributeBinding idAttributeBinding = entityBinding.getAttributeBinding( "id" );
assertNotNull( idAttributeBinding );
@ -137,4 +138,9 @@ protected void assertIdAndSimpleProperty(EntityBinding entityBinding) {
assertNotNull( nameBinding.getAttribute() );
assertNotNull( nameBinding.getValue() );
}
protected void assertRoot(MetadataImplementor metadata, EntityBinding entityBinding) {
assertTrue( entityBinding.isRoot() );
assertSame( entityBinding, metadata.getRootEntityBinding( entityBinding.getEntity().getName() ) );
}
}

View File

@ -57,6 +57,14 @@ public EntityBinding getEntityBinding(Class<?> clazz) {
}
return meta.getEntityBinding( clazz.getName() );
}
public EntityBinding getRootEntityBinding(Class<?> clazz) {
if ( meta == null ) {
meta = (MetadataImpl) sources.buildMetadata();
}
return meta.getRootEntityBinding( clazz.getName() );
}
}

View File

@ -34,6 +34,7 @@
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertSame;
import static junit.framework.Assert.assertTrue;
/**
@ -44,7 +45,6 @@ public class InheritanceTypeTest extends BaseAnnotationBindingTestCase {
public void testNoInheritance() {
buildMetadataSources( SingleEntity.class );
EntityBinding entityBinding = getEntityBinding( SingleEntity.class );
assertTrue( entityBinding.isRoot() );
assertNull( entityBinding.getEntityDiscriminator() );
}
@ -54,10 +54,29 @@ public void testDiscriminatorValue() {
RootOfSingleTableInheritance.class, SubclassOfSingleTableInheritance.class
);
EntityBinding entityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
assertFalse( entityBinding.isRoot() );
assertEquals( "Wrong discriminator value", "foo", entityBinding.getDiscriminatorValue() );
}
@Test
public void testRootEntityBinding() {
buildMetadataSources(
SubclassOfSingleTableInheritance.class, SingleEntity.class, RootOfSingleTableInheritance.class
);
EntityBinding noInheritanceEntityBinding = getEntityBinding( SingleEntity.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
assertTrue( noInheritanceEntityBinding.isRoot() );
assertSame( noInheritanceEntityBinding, getRootEntityBinding( SingleEntity.class ) );
assertFalse( subclassEntityBinding.isRoot() );
assertSame( rootEntityBinding, getRootEntityBinding( SubclassOfSingleTableInheritance.class ) );
assertTrue( rootEntityBinding.isRoot() );
assertSame( rootEntityBinding, getRootEntityBinding( RootOfSingleTableInheritance.class ));
}
@Entity
class SingleEntity {
@Id

View File

@ -27,14 +27,21 @@
import org.junit.Test;
import org.hibernate.EmptyInterceptor;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.metamodel.Metadata;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertSame;
import static junit.framework.Assert.assertTrue;
/**
@ -81,6 +88,19 @@ public void testAddingPackageNameWithTrailingDot() {
assertFetchProfile( metadata );
}
@Test
public void testGettingSessionFactoryBuilder() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
Metadata metadata = sources.buildMetadata();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
assertNotNull( sessionFactoryBuilder );
assertTrue( SessionFactoryBuilderImpl.class.isInstance( sessionFactoryBuilder ) );
SessionFactory sessionFactory = metadata.buildSessionFactory();
assertNotNull( sessionFactory );
}
private void assertFetchProfile(MetadataImpl metadata) {
Iterator<FetchProfile> profiles = metadata.getFetchProfiles().iterator();
assertTrue( profiles.hasNext() );

View File

@ -0,0 +1,194 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.internal;
import java.io.Serializable;
import java.util.Iterator;
import org.junit.Test;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.EntityMode;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.type.Type;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertSame;
import static junit.framework.Assert.assertTrue;
/**
* @author Gail Badner
*/
public class SessionFactoryBuilderImplTest extends BaseUnitTestCase {
@Test
public void testGettingSessionFactoryBuilder() {
SessionFactoryBuilder sessionFactoryBuilder = getSessionFactoryBuilder();
assertNotNull( sessionFactoryBuilder );
assertTrue( SessionFactoryBuilderImpl.class.isInstance( sessionFactoryBuilder ) );
}
@Test
public void testBuildSessionFactoryWithDefaultOptions() {
SessionFactoryBuilder sessionFactoryBuilder = getSessionFactoryBuilder();
SessionFactory sessionFactory = sessionFactoryBuilder.buildSessionFactory();
assertSame( EmptyInterceptor.INSTANCE, sessionFactory.getSessionFactoryOptions().getInterceptor() );
assertTrue( EntityNotFoundDelegate.class.isInstance(
sessionFactory.getSessionFactoryOptions().getEntityNotFoundDelegate()
) );
}
@Test
public void testBuildSessionFactoryWithUpdatedOptions() {
SessionFactoryBuilder sessionFactoryBuilder = getSessionFactoryBuilder();
Interceptor interceptor = new AnInterceptor();
EntityNotFoundDelegate entityNotFoundDelegate = new EntityNotFoundDelegate() {
@Override
public void handleEntityNotFound(String entityName, Serializable id) {
throw new ObjectNotFoundException( id, entityName );
}
};
sessionFactoryBuilder.with( interceptor );
sessionFactoryBuilder.with( entityNotFoundDelegate );
SessionFactory sessionFactory = sessionFactoryBuilder.buildSessionFactory();
assertSame( interceptor, sessionFactory.getSessionFactoryOptions().getInterceptor() );
assertSame( entityNotFoundDelegate, sessionFactory.getSessionFactoryOptions().getEntityNotFoundDelegate() );
}
private SessionFactoryBuilder getSessionFactoryBuilder() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static class AnInterceptor implements Interceptor {
private static final Interceptor INSTANCE = EmptyInterceptor.INSTANCE;
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return INSTANCE.onLoad( entity, id, state, propertyNames, types );
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
throws CallbackException {
return INSTANCE.onFlushDirty( entity, id, currentState, previousState, propertyNames, types );
}
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return INSTANCE.onSave( entity, id, state, propertyNames, types );
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
INSTANCE.onDelete( entity, id, state, propertyNames, types );
}
@Override
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
INSTANCE.onCollectionRecreate( collection, key );
}
@Override
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
INSTANCE.onCollectionRemove( collection, key );
}
@Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
INSTANCE.onCollectionUpdate( collection, key );
}
@Override
public void preFlush(Iterator entities) throws CallbackException {
INSTANCE.preFlush( entities );
}
@Override
public void postFlush(Iterator entities) throws CallbackException {
INSTANCE.postFlush( entities );
}
@Override
public Boolean isTransient(Object entity) {
return INSTANCE.isTransient( entity );
}
@Override
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
return INSTANCE.findDirty( entity, id, currentState, previousState, propertyNames, types );
}
@Override
public Object instantiate(String entityName, EntityMode entityMode, Serializable id)
throws CallbackException {
return INSTANCE.instantiate( entityName, entityMode, id );
}
@Override
public String getEntityName(Object object) throws CallbackException {
return INSTANCE.getEntityName( object );
}
@Override
public Object getEntity(String entityName, Serializable id) throws CallbackException {
return INSTANCE.getEntity( entityName, id );
}
@Override
public void afterTransactionBegin(Transaction tx) {
INSTANCE.afterTransactionBegin( tx );
}
@Override
public void beforeTransactionCompletion(Transaction tx) {
INSTANCE.beforeTransactionCompletion( tx );
}
@Override
public void afterTransactionCompletion(Transaction tx) {
INSTANCE.afterTransactionCompletion( tx );
}
@Override
public String onPrepareStatement(String sql) {
return INSTANCE.onPrepareStatement( sql );
}
}
}