Merge commit 'upstream/master' into HHH-6176

This commit is contained in:
Michal Skowronek 2011-05-21 14:43:07 +02:00
commit 71a256624f
117 changed files with 2350 additions and 1800 deletions

View File

@ -163,6 +163,7 @@ subprojects { subProject ->
compilerArgs: [
"-nowarn",
"-proc:only",
"-encoding", "UTF-8",
"-processor", "org.jboss.logging.LoggingToolsProcessor",
"-s", "$sourceSets.main.generatedLoggingSrcDir.absolutePath"
]
@ -177,7 +178,7 @@ subprojects { subProject ->
generateMainLoggingClasses.logging.captureStandardError(LogLevel.INFO)
compileJava.dependsOn generateMainLoggingClasses
compileJava.options.define(compilerArgs: ["-proc:none"])
compileJava.options.define(compilerArgs: ["-proc:none", "-encoding", "UTF-8"])
manifest.mainAttributes(
provider: 'gradle',

View File

@ -22,24 +22,23 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Whether or not update entity's version on property's change
* If the annotation is not present, the property is involved in the optimistic lock srategy (default)
* Whether or not a change of the annotated property will trigger a entity version increment.
* If the annotation is not present, the property is involved in the optimistic lock strategy (default).
*
* @author Logi Ragnarsson
*/
@Target( {ElementType.METHOD, ElementType.FIELD} )
@Retention( RetentionPolicy.RUNTIME )
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface OptimisticLock {
/**
* If true, the annotated property change will not trigger a version upgrade
* @return If {@code true}, the annotated property change will not trigger a version increment.
*/
boolean excluded();
}

View File

@ -59,6 +59,7 @@ import org.hibernate.type.BasicType;
import org.hibernate.type.SerializationException;
import org.hibernate.type.Type;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
@ -115,7 +116,7 @@ public interface CoreMessageLogger extends BasicLogger {
@Message(value = "Cleaning up connection pool [%s]", id = 30)
void cleaningUpConnectionPool(String url);
@LogMessage(level = INFO)
@LogMessage(level = DEBUG)
@Message(value = "Closing", id = 31)
void closing();
@ -539,11 +540,11 @@ public interface CoreMessageLogger extends BasicLogger {
@Message(value = "Logging statistics....", id = 161)
void loggingStatistics();
@LogMessage(level = INFO)
@LogMessage(level = DEBUG)
@Message(value = "*** Logical connection closed ***", id = 162)
void logicalConnectionClosed();
@LogMessage(level = INFO)
@LogMessage(level = DEBUG)
@Message(value = "Logical connection releasing its physical connection", id = 163)
void logicalConnectionReleasingPhysicalConnection();

View File

@ -232,6 +232,18 @@ public final class ReflectHelper {
}
}
/**
* Attempt to resolve the specified property type through reflection.
*
* @param clazz The class owning the property.
* @param name The name of the property.
* @return The type of the property.
* @throws MappingException Indicates we were unable to locate the property.
*/
public static Class reflectedPropertyClass(Class clazz, String name) throws MappingException {
return getter( clazz, name ).getReturnType();
}
private static Getter getter(Class clazz, String name) throws MappingException {
try {
return BASIC_PROPERTY_ACCESSOR.getGetter( clazz, name );

View File

@ -24,9 +24,28 @@
package org.hibernate.metamodel;
import javax.persistence.SharedCacheMode;
import org.hibernate.SessionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.NamingStrategy;
/**
* @author Steve Ebersole
*/
public interface Metadata {
/**
* Exposes the options used to produce a {@link Metadata} instance.
*/
public static interface Options {
public SourceProcessingOrder getSourceProcessingOrder();
public NamingStrategy getNamingStrategy();
public SharedCacheMode getSharedCacheMode();
public AccessType getDefaultAccessType();
public boolean useNewIdentifierGenerators();
}
public Options getOptions();
public SessionFactory buildSessionFactory();
}

View File

@ -25,6 +25,7 @@ package org.hibernate.metamodel;
import javax.persistence.SharedCacheMode;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.NamingStrategy;
/**
@ -38,5 +39,9 @@ public interface MetadataBuilder {
public MetadataBuilder with(SharedCacheMode cacheMode);
public MetadataBuilder with(AccessType accessType);
public MetadataBuilder withNewIdentifierGeneratorsEnabled(boolean enabled);
public Metadata buildMetadata();
}

View File

@ -30,6 +30,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.MappingException;
import org.hibernate.metamodel.binding.state.AttributeBindingState;
import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.relational.Column;
@ -38,10 +40,10 @@ import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.relational.Tuple;
import org.hibernate.metamodel.relational.Value;
import org.hibernate.metamodel.relational.ValueFactory;
import org.hibernate.metamodel.state.domain.AttributeDomainState;
import org.hibernate.metamodel.state.relational.ValueRelationalState;
import org.hibernate.metamodel.state.relational.TupleRelationalState;
import org.hibernate.metamodel.relational.state.SimpleValueRelationalState;
import org.hibernate.metamodel.relational.state.TupleRelationalState;
import org.hibernate.metamodel.relational.state.ValueCreator;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
/**
* TODO : javadoc
@ -49,11 +51,9 @@ import org.hibernate.metamodel.state.relational.TupleRelationalState;
* @author Steve Ebersole
*/
public abstract class AbstractAttributeBinding implements AttributeBinding {
private final HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
private final EntityBinding entityBinding;
private final Set<EntityReferencingAttributeBinding> entityReferencingAttributeBindings =
new HashSet<EntityReferencingAttributeBinding>();
private final Set<EntityReferencingAttributeBinding> entityReferencingAttributeBindings = new HashSet<EntityReferencingAttributeBinding>();
private Attribute attribute;
private Value value;
@ -73,9 +73,9 @@ public abstract class AbstractAttributeBinding implements AttributeBinding {
this.entityBinding = entityBinding;
}
protected void initialize(AttributeDomainState state) {
hibernateTypeDescriptor.initialize( state.getHibernateTypeDescriptor() );
attribute = state.getAttribute();
protected void initialize(AttributeBindingState state) {
hibernateTypeDescriptor.setTypeName( state.getTypeName() );
hibernateTypeDescriptor.setTypeParameters( state.getTypeParameters() );
isLazy = state.isLazy();
propertyAccessorName = state.getPropertyAccessorName();
isAlternateUniqueKey = state.isAlternateUniqueKey();
@ -107,24 +107,37 @@ public abstract class AbstractAttributeBinding implements AttributeBinding {
return false;
}
protected void initializeValue(ValueRelationalState state) {
value = ValueFactory.createValue( getEntityBinding().getBaseTable(),
protected final boolean isPrimaryKey() {
return this == getEntityBinding().getEntityIdentifier().getValueBinding();
}
protected void initializeValueRelationalState(ValueRelationalState state) {
// TODO: change to have ValueRelationalState generate the value
value = ValueCreator.createValue(
getEntityBinding().getBaseTable(),
getAttribute().getName(),
convertToSimpleRelationalStateIfPossible( state ),
state,
forceNonNullable(),
forceUnique()
);
}
// TODO: should a single-valued tuple always be converted???
protected ValueRelationalState convertToSimpleRelationalStateIfPossible(ValueRelationalState state) {
if ( !TupleRelationalState.class.isInstance( state ) ) {
return state;
// TODO: not sure I like this here...
if ( isPrimaryKey() ) {
if ( SimpleValue.class.isInstance( value ) ) {
if ( !Column.class.isInstance( value ) ) {
// this should never ever happen..
throw new MappingException( "Simple ID is not a column." );
}
entityBinding.getBaseTable().getPrimaryKey().addColumn( Column.class.cast( value ) );
}
else {
for ( SimpleValueRelationalState val : TupleRelationalState.class.cast( state )
.getRelationalStates() ) {
if ( Column.class.isInstance( val ) ) {
entityBinding.getBaseTable().getPrimaryKey().addColumn( Column.class.cast( val ) );
}
}
}
}
TupleRelationalState tupleRelationalState = TupleRelationalState.class.cast( state );
return tupleRelationalState.getRelationalStates().size() == 1 ?
tupleRelationalState.getRelationalStates().get( 0 ) :
state;
}
@Override
@ -145,10 +158,6 @@ public abstract class AbstractAttributeBinding implements AttributeBinding {
return optimisticLockable;
}
public String getNodeName() {
return nodeName;
}
@Override
public Map<String, MetaAttribute> getMetaAttributes() {
return metaAttributes;
@ -159,13 +168,8 @@ public abstract class AbstractAttributeBinding implements AttributeBinding {
return value == null
? Collections.<SimpleValue>emptyList()
: value instanceof Tuple
? ( (Tuple) value ).values()
: Collections.singletonList( (SimpleValue) value );
}
@Override
public TableSpecification getTable() {
return getValue().getTable();
? ( (Tuple) value ).values()
: Collections.singletonList( (SimpleValue) value );
}
@Override
@ -210,9 +214,9 @@ public abstract class AbstractAttributeBinding implements AttributeBinding {
public boolean[] getColumnInsertability() {
List<Boolean> tmp = new ArrayList<Boolean>();
for ( SimpleValue simpleValue : getValues() ) {
tmp.add( ! ( simpleValue instanceof DerivedValue ) );
tmp.add( !( simpleValue instanceof DerivedValue ) );
}
boolean[] rtn = new boolean[ tmp.size() ];
boolean[] rtn = new boolean[tmp.size()];
int i = 0;
for ( Boolean insertable : tmp ) {
rtn[i++] = insertable.booleanValue();
@ -243,11 +247,10 @@ public abstract class AbstractAttributeBinding implements AttributeBinding {
}
public void validate() {
if ( ! entityReferencingAttributeBindings.isEmpty() ) {
if ( !entityReferencingAttributeBindings.isEmpty() ) {
// TODO; validate that this AttributeBinding can be a target of an entity reference
// (e.g., this attribute is the primary key or there is a unique-key)
// can a unique attribute be used as a target? if so, does it need to be non-null?
}
}
}

View File

@ -74,27 +74,14 @@ public interface AttributeBinding {
public Map<String, MetaAttribute> getMetaAttributes();
/**
* In the case that {@link #getValue()} represents a {@link org.hibernate.metamodel.relational.Tuple} this method
* @return In the case that {@link #getValue()} represents a {@link org.hibernate.metamodel.relational.Tuple} this method
* gives access to its compound values. In the case of {@link org.hibernate.metamodel.relational.SimpleValue},
* we return an Iterable over that single simple value.
*
* @return
*/
public Iterable<SimpleValue> getValues();
/**
* @return
*
* @deprecated Use {@link #getValue()}.{@link Value#getTable() getTable()} instead; to be removed on completion of new metamodel code
*/
@Deprecated
public TableSpecification getTable();
public String getPropertyAccessorName();
/**
* @return
*/
public boolean hasFormula();
public boolean isAlternateUniqueKey();

View File

@ -23,6 +23,8 @@
*/
package org.hibernate.metamodel.binding;
import org.hibernate.metamodel.binding.state.PluralAttributeBindingState;
/**
* TODO : javadoc
*
@ -32,4 +34,9 @@ public class BagBinding extends PluralAttributeBinding {
protected BagBinding(EntityBinding entityBinding) {
super( entityBinding );
}
public BagBinding initialize(PluralAttributeBindingState bindingState) {
super.initialize( bindingState );
return this;
}
}

View File

@ -24,7 +24,6 @@
package org.hibernate.metamodel.binding;
import org.hibernate.metamodel.relational.Value;
import org.hibernate.metamodel.state.domain.CollectionElementDomainState;
/**
* TODO : javadoc
@ -44,8 +43,13 @@ public class CollectionElement {
this.collectionBinding = collectionBinding;
}
public void initialize(CollectionElementDomainState state) {
hibernateTypeDescriptor.initialize( state.getHibernateTypeDescriptor() );
nodeName = state.getNodeName();
/* package-protected */
void setTypeName(String typeName) {
hibernateTypeDescriptor.setTypeName( typeName );
}
/* package-protected */
void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
}

View File

@ -39,12 +39,13 @@ import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlDeleteElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlInsertElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlUpdateElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSynchronizeElement;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
/**
* Provides the link between the domain and the relational model for an entity.
@ -207,16 +208,6 @@ public class EntityBinding {
return entityDiscriminator;
}
public void bindEntityDiscriminator(SimpleAttributeBinding attributeBinding) {
if ( !Column.class.isInstance( attributeBinding.getValue() ) ) {
throw new MappingException(
"Identifier value must be a Column; instead it is: " + attributeBinding.getValue().getClass()
);
}
entityDiscriminator.setValueBinding( attributeBinding );
baseTable.getPrimaryKey().addColumn( Column.class.cast( attributeBinding.getValue() ) );
}
public void setInheritanceType(InheritanceType entityInheritanceType) {
this.entityInheritanceType = entityInheritanceType;
}
@ -241,27 +232,26 @@ public class EntityBinding {
return entityReferencingAttributeBindings;
}
public SimpleAttributeBinding makeSimplePrimaryKeyAttributeBinding(String name) {
public SimpleAttributeBinding makeSimpleIdAttributeBinding(String name) {
final SimpleAttributeBinding binding = makeSimpleAttributeBinding( name, true, true );
getEntityIdentifier().setValueBinding( binding );
return binding;
}
public SimpleAttributeBinding makeEntityDiscriminatorBinding(String name) {
public EntityDiscriminator makeEntityDiscriminator(String attributeName) {
if ( entityDiscriminator != null ) {
throw new AssertionFailure( "Creation of entity discriminator was called more than once" );
}
entityDiscriminator = new EntityDiscriminator();
entityDiscriminator.setValueBinding( makeSimpleAttributeBinding( name, true, false ) );
return entityDiscriminator.getValueBinding();
entityDiscriminator.setValueBinding( makeSimpleAttributeBinding( attributeName, true, false ) );
return entityDiscriminator;
}
public SimpleAttributeBinding makeVersionBinding(String name) {
versionBinding = makeSimpleAttributeBinding( name, true, false );
public SimpleAttributeBinding makeVersionBinding(String attributeName) {
versionBinding = makeSimpleAttributeBinding( attributeName, true, false );
return versionBinding;
}
public SimpleAttributeBinding makeSimpleAttributeBinding(String name) {
return makeSimpleAttributeBinding( name, false, false );
}
@ -273,17 +263,17 @@ public class EntityBinding {
return binding;
}
public ManyToOneAttributeBinding makeManyToOneAttributeBinding(String name) {
public ManyToOneAttributeBinding makeManyToOneAttributeBinding(String attributeName) {
final ManyToOneAttributeBinding binding = new ManyToOneAttributeBinding( this );
registerAttributeBinding( name, binding );
binding.setAttribute( entity.getAttribute( name ) );
registerAttributeBinding( attributeName, binding );
binding.setAttribute( entity.getAttribute( attributeName ) );
return binding;
}
public BagBinding makeBagAttributeBinding(String name) {
public BagBinding makeBagAttributeBinding(String attributeName) {
final BagBinding binding = new BagBinding( this );
registerAttributeBinding( name, binding );
binding.setAttribute( entity.getAttribute( name ) );
registerAttributeBinding( attributeName, binding );
binding.setAttribute( entity.getAttribute( attributeName ) );
return binding;
}

View File

@ -23,6 +23,9 @@
*/
package org.hibernate.metamodel.binding;
import org.hibernate.metamodel.binding.state.DiscriminatorBindingState;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
/**
* Binding of the discriminator in a entity hierarchy
*
@ -40,10 +43,26 @@ public class EntityDiscriminator {
return valueBinding;
}
public void setValueBinding(SimpleAttributeBinding valueBinding) {
/* package-protected */
void setValueBinding(SimpleAttributeBinding valueBinding) {
this.valueBinding = valueBinding;
}
public EntityDiscriminator initialize(DiscriminatorBindingState state) {
if ( valueBinding == null ) {
throw new IllegalStateException( "Cannot bind state because the value binding has not been initialized." );
}
this.valueBinding.initialize( state );
this.forced = state.isForced();
this.inserted = state.isInsertable();
return this;
}
public EntityDiscriminator initialize(ValueRelationalState state) {
valueBinding.initialize( state );
return this;
}
public boolean isForced() {
return forced;
}

View File

@ -23,7 +23,7 @@
*/
package org.hibernate.metamodel.binding;
import java.util.Properties;
import java.util.Map;
import org.hibernate.type.Type;
@ -35,12 +35,13 @@ import org.hibernate.type.Type;
public class HibernateTypeDescriptor {
private String typeName;
private Type explicitType;
private Properties typeParameters;
private Map<String, String> typeParameters;
public String getTypeName() {
return typeName;
}
/* package-protected */
public void setTypeName(String typeName) {
this.typeName = typeName;
}
@ -49,13 +50,17 @@ public class HibernateTypeDescriptor {
return explicitType;
}
/* package-protected */
public void setExplicitType(Type explicitType) {
this.explicitType = explicitType;
}
public void initialize(HibernateTypeDescriptor hibernateTypeDescriptor) {
typeName = hibernateTypeDescriptor.typeName;
explicitType = hibernateTypeDescriptor.explicitType;
typeParameters = hibernateTypeDescriptor.typeParameters;
public Map<String, String> getTypeParameters() {
return typeParameters;
}
/* package-protected */
void setTypeParameters(Map<String, String> typeParameters) {
this.typeParameters = typeParameters;
}
}

View File

@ -29,9 +29,9 @@ package org.hibernate.metamodel.binding;
* @author Steve Ebersole
*/
public interface KeyValueBinding extends AttributeBinding {
public boolean isKeyCasadeDeleteEnabled();
public boolean isKeyCascadeDeleteEnabled();
public String getUnsavedValue();
public boolean isUpdateable();
public boolean isUpdatable();
}

View File

@ -26,19 +26,18 @@ package org.hibernate.metamodel.binding;
import java.util.Iterator;
import org.hibernate.MappingException;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.metamodel.binding.state.ManyToOneAttributeBindingState;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.ForeignKey;
import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.state.domain.ManyToOneAttributeDomainState;
import org.hibernate.metamodel.state.relational.ManyToOneRelationalState;
import org.hibernate.metamodel.relational.state.ManyToOneRelationalState;
/**
* TODO : javadoc
*
* @author Gail Badner
*/
public class ManyToOneAttributeBinding extends SingularAttributeBinding implements EntityReferencingAttributeBinding {
public class ManyToOneAttributeBinding extends SimpleAttributeBinding implements EntityReferencingAttributeBinding {
private boolean isLogicalOneToOne;
private boolean isPropertyReference;
private String foreignKeyName;
@ -51,24 +50,19 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
super( entityBinding, false, false );
}
public final void initialize(ManyToOneAttributeDomainState state) {
public final ManyToOneAttributeBinding initialize(ManyToOneAttributeBindingState state) {
super.initialize( state );
isPropertyReference = state.getReferencedAttributeName() != null;
referencedAttributeName = state.getReferencedAttributeName();
referencedEntityName = state.getReferencedEntityName();
if ( referencedEntityName == null ) {
referencedEntityName =
ReflectHelper.reflectedPropertyClass(
getEntityBinding().getEntity().getName(),
state.getAttribute().getName()
).getName();
}
return this;
}
public final void initialize(ManyToOneRelationalState state) {
super.initializeValue( state );
public final ManyToOneAttributeBinding initialize(ManyToOneRelationalState state) {
super.initializeValueRelationalState( state );
isLogicalOneToOne = state.isLogicalOneToOne();
foreignKeyName = state.getForeignKeyName();
return this;
}
public final boolean isPropertyReference() {
@ -82,7 +76,7 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
public final String getReferencedAttributeName() {
if ( referencedAttributeName == null ) {
throw new IllegalStateException(
"Referenced attribute name is not available."
"Referenced attribute name is not available."
);
}
return referencedAttributeName;
@ -93,7 +87,7 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
}
public final EntityBinding getReferencedEntityBinding() {
if ( ! isReferenceResolved() ) {
if ( !isReferenceResolved() ) {
throw new IllegalStateException( "EntityBinding reference has not be referenced." );
}
// TODO: throw exception if referencedEntityBinding is null?
@ -101,7 +95,7 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
}
public final void resolveReference(AttributeBinding referencedAttributeBinding) {
if ( ! referencedEntityName.equals( referencedAttributeBinding.getEntityBinding().getEntity().getName() ) ) {
if ( !referencedEntityName.equals( referencedAttributeBinding.getEntityBinding().getEntity().getName() ) ) {
throw new IllegalStateException(
"attempt to set EntityBinding with name: [" +
referencedAttributeBinding.getEntityBinding().getEntity().getName() +
@ -111,10 +105,10 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
if ( referencedAttributeName == null ) {
referencedAttributeName = referencedAttributeBinding.getAttribute().getName();
}
else if ( ! referencedAttributeName.equals( referencedAttributeBinding.getAttribute().getName() ) ) {
else if ( !referencedAttributeName.equals( referencedAttributeBinding.getAttribute().getName() ) ) {
throw new IllegalStateException(
"Inconsistent attribute name; expected: " + referencedAttributeName +
"actual: " + referencedAttributeBinding.getAttribute().getName()
"actual: " + referencedAttributeBinding.getAttribute().getName()
);
}
this.referencedAttributeBinding = referencedAttributeBinding;
@ -123,18 +117,21 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
private void buildForeignKey() {
// TODO: move this stuff to relational model
ForeignKey foreignKey = getTable().createForeignKey( referencedAttributeBinding.getTable(), foreignKeyName );
ForeignKey foreignKey = getValue().getTable()
.createForeignKey( referencedAttributeBinding.getValue().getTable(), foreignKeyName );
Iterator<SimpleValue> referencingValueIterator = getValues().iterator();
Iterator<SimpleValue> targetValueIterator = referencedAttributeBinding.getValues().iterator();
Iterator<SimpleValue> targetValueIterator = referencedAttributeBinding.getValues().iterator();
while ( referencingValueIterator.hasNext() ) {
if ( ! targetValueIterator.hasNext() ) {
if ( !targetValueIterator.hasNext() ) {
// TODO: improve this message
throw new MappingException( "number of values in many-to-one reference is greater than number of values in target" );
throw new MappingException(
"number of values in many-to-one reference is greater than number of values in target"
);
}
SimpleValue referencingValue = referencingValueIterator.next();
SimpleValue targetValue = targetValueIterator.next();
if ( Column.class.isInstance( referencingValue ) ) {
if ( ! Column.class.isInstance( targetValue ) ) {
if ( !Column.class.isInstance( targetValue ) ) {
// TODO improve this message
throw new MappingException( "referencing value is a column, but target is not a column" );
}
@ -157,7 +154,7 @@ public class ManyToOneAttributeBinding extends SingularAttributeBinding implemen
public void validate() {
// can't check this until both the domain and relational states are initialized...
if ( getCascade() != null && getCascade().indexOf( "delete-orphan" ) >= 0 ) {
if ( ! isLogicalOneToOne ) {
if ( !isLogicalOneToOne ) {
throw new MappingException(
"many-to-one attribute [" + getAttribute().getName() + "] does not support orphan delete as it is not unique"
);

View File

@ -31,8 +31,8 @@ import org.jboss.logging.Logger;
import org.hibernate.FetchMode;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.metamodel.binding.state.PluralAttributeBindingState;
import org.hibernate.metamodel.relational.Table;
import org.hibernate.metamodel.state.domain.PluralAttributeDomainState;
/**
* TODO : javadoc
@ -84,12 +84,13 @@ public abstract class PluralAttributeBinding extends AbstractAttributeBinding {
collectionElement = new CollectionElement( this );
}
public void initialize(PluralAttributeDomainState state) {
protected void initializeBinding(PluralAttributeBindingState state) {
super.initialize( state );
fetchMode = state.getFetchMode();
extraLazy = state.isExtraLazy();
collectionElement = new ElementCollectionElement( this );
collectionElement.initialize( state.getCollectionElementDomainState() );
collectionElement.setNodeName( state.getElementNodeName() );
collectionElement.setTypeName( state.getElementTypeName() );
inverse = state.isInverse();
mutable = state.isMutable();
subselectLoadable = state.isSubselectLoadable();
@ -118,10 +119,6 @@ public abstract class PluralAttributeBinding extends AbstractAttributeBinding {
loaderName = state.getLoaderName();
}
protected boolean isLazyDefault(MappingDefaults defaults) {
return defaults.isDefaultLazy();
}
@Override
public boolean isSimpleValue() {
return false;

View File

@ -24,38 +24,43 @@
package org.hibernate.metamodel.binding;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.state.domain.SimpleAttributeDomainState;
import org.hibernate.metamodel.state.relational.ColumnRelationalState;
import org.hibernate.metamodel.state.relational.DerivedValueRelationalState;
import org.hibernate.metamodel.state.relational.TupleRelationalState;
import org.hibernate.metamodel.binding.state.SimpleAttributeBindingState;
import org.hibernate.metamodel.relational.state.ColumnRelationalState;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
public class SimpleAttributeBinding extends SingularAttributeBinding {
public class SimpleAttributeBinding extends AbstractAttributeBinding implements KeyValueBinding {
private final boolean forceNonNullable;
private final boolean forceUnique;
private boolean insertable;
private boolean updatable;
private boolean keyCascadeDeleteEnabled;
private String unsavedValue;
private PropertyGeneration generation;
SimpleAttributeBinding(EntityBinding entityBinding, boolean forceNonNullable, boolean forceUnique) {
super( entityBinding, forceNonNullable, forceUnique );
super( entityBinding );
this.forceNonNullable = forceNonNullable;
this.forceUnique = forceUnique;
}
public final void initialize(SimpleAttributeDomainState state) {
public final SimpleAttributeBinding initialize(SimpleAttributeBindingState state) {
super.initialize( state );
generation = state.getPropertyGeneration();
insertable = state.isInsertable();
updatable = state.isUpdatable();
keyCascadeDeleteEnabled = state.isKeyCascadeDeleteEnabled();
unsavedValue = state.getUnsavedValue();
generation = state.getPropertyGeneration() == null ? PropertyGeneration.NEVER : state.getPropertyGeneration();
return this;
}
public void initializeColumnValue(ColumnRelationalState state) {
super.initializeValue( state );
}
public void initializeDerivedValue(DerivedValueRelationalState state) {
super.initializeValue( state );
}
public void initializeTupleValue(TupleRelationalState state) {
super.initializeValue( state );
public SimpleAttributeBinding initialize(ValueRelationalState state) {
super.initializeValueRelationalState( state );
return this;
}
private boolean isUnique(ColumnRelationalState state) {
@ -67,12 +72,49 @@ public class SimpleAttributeBinding extends SingularAttributeBinding {
return true;
}
private boolean isPrimaryKey() {
return this == getEntityBinding().getEntityIdentifier().getValueBinding();
public boolean isInsertable() {
return insertable;
}
protected void setInsertable(boolean insertable) {
this.insertable = insertable;
}
public boolean isUpdatable() {
return updatable;
}
protected void setUpdatable(boolean updatable) {
this.updatable = updatable;
}
@Override
public boolean isKeyCascadeDeleteEnabled() {
return keyCascadeDeleteEnabled;
}
public void setKeyCascadeDeleteEnabled(boolean keyCascadeDeleteEnabled) {
this.keyCascadeDeleteEnabled = keyCascadeDeleteEnabled;
}
@Override
public String getUnsavedValue() {
return unsavedValue;
}
public void setUnsavedValue(String unsaveValue) {
this.unsavedValue = unsaveValue;
}
public boolean forceNonNullable() {
return forceNonNullable;
}
public boolean forceUnique() {
return forceUnique;
}
public PropertyGeneration getGeneration() {
return generation;
}
}

View File

@ -1,96 +0,0 @@
/*
* 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.binding;
import org.hibernate.metamodel.state.domain.SingularAttributeDomainState;
/**
* TODO : javadoc
*
* @author Gail Badner
*/
public abstract class SingularAttributeBinding extends AbstractAttributeBinding implements KeyValueBinding {
private final boolean forceNonNullable;
private final boolean forceUnique;
private boolean insertable;
private boolean updateable;
private boolean keyCasadeDeleteEnabled;
private String unsavedValue;
SingularAttributeBinding(EntityBinding entityBinding, boolean forceNonNullable, boolean forceUnique) {
super( entityBinding );
this.forceNonNullable = forceNonNullable;
this.forceUnique = forceUnique;
}
public final void initialize(SingularAttributeDomainState state) {
super.initialize( state );
insertable = state.isInsertable();
updateable = state.isUpdateable();
keyCasadeDeleteEnabled = state.isKeyCasadeDeleteEnabled();
unsavedValue = state.getUnsavedValue();
}
public boolean isInsertable() {
return insertable;
}
protected void setInsertable(boolean insertable) {
this.insertable = insertable;
}
public boolean isUpdateable() {
return updateable;
}
protected void setUpdateable(boolean updateable) {
this.updateable = updateable;
}
@Override
public boolean isKeyCasadeDeleteEnabled() {
return keyCasadeDeleteEnabled;
}
public void setKeyCasadeDeleteEnabled(boolean keyCasadeDeleteEnabled) {
this.keyCasadeDeleteEnabled = keyCasadeDeleteEnabled;
}
@Override
public String getUnsavedValue() {
return unsavedValue;
}
public void setUnsavedValue(String unsaveValue) {
this.unsavedValue = unsaveValue;
}
public boolean forceNonNullable() {
return forceNonNullable;
}
public boolean forceUnique() {
return forceUnique;
}
}

View File

@ -21,25 +21,33 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.domain;
package org.hibernate.metamodel.binding.state;
import java.util.Map;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.MetaAttribute;
/**
* @author Gail Badner
*/
public interface AttributeDomainState {
HibernateTypeDescriptor getHibernateTypeDescriptor();
Attribute getAttribute();
public interface AttributeBindingState {
String getAttributeName();
String getTypeName();
Map<String, String> getTypeParameters();
boolean isLazy();
String getPropertyAccessorName();
boolean isAlternateUniqueKey();
String getCascade();
boolean isOptimisticLockable();
String getNodeName();
Map<String, MetaAttribute> getMetaAttributes();
}

View File

@ -21,14 +21,11 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.domain;
package org.hibernate.metamodel.binding.state;
/**
* @author Gail Badner
*/
public interface SingularAttributeDomainState extends AttributeDomainState{
boolean isInsertable();
boolean isUpdateable();
boolean isKeyCasadeDeleteEnabled();
String getUnsavedValue();
public interface DiscriminatorBindingState extends SimpleAttributeBindingState {
boolean isForced();
}

View File

@ -21,14 +21,17 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.domain;
package org.hibernate.metamodel.binding.state;
/**
* @author Gail Badner
*/
public interface ManyToOneAttributeDomainState extends SingularAttributeDomainState {
public interface ManyToOneAttributeBindingState extends SimpleAttributeBindingState {
boolean isUnwrapProxy();
String getReferencedAttributeName();
String getReferencedEntityName();
boolean ignoreNotFound();
}

View File

@ -21,48 +21,68 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.domain;
package org.hibernate.metamodel.binding.state;
import java.util.Comparator;
import org.hibernate.FetchMode;
import org.hibernate.metamodel.binding.AbstractAttributeBinding;
import org.hibernate.metamodel.binding.CollectionElement;
import org.hibernate.metamodel.binding.CustomSQL;
import org.hibernate.metamodel.binding.PluralAttributeBinding;
/**
* Created by IntelliJ IDEA.
* User: gbadner
* Date: 5/9/11
* Time: 4:49 PM
* To change this template use File | Settings | File Templates.
* @author gbadner
*/
public interface PluralAttributeDomainState extends AttributeDomainState {
public interface PluralAttributeBindingState extends AttributeBindingState {
FetchMode getFetchMode();
boolean isExtraLazy();
CollectionElementDomainState getCollectionElementDomainState();
String getElementTypeName();
String getElementNodeName();
boolean isInverse();
boolean isMutable();
boolean isSubselectLoadable();
String getCacheConcurrencyStrategy();
String getCacheRegionName();
String getOrderBy();
String getWhere();
String getReferencedPropertyName();
boolean isSorted();
Comparator getComparator();
String getComparatorClassName();
boolean isOrphanDelete();
int getBatchSize();
boolean isEmbedded();
boolean isOptimisticLocked();
Class getCollectionPersisterClass();
java.util.Map getFilters();
java.util.Set getSynchronizedTables();
CustomSQL getCustomSQLInsert();
CustomSQL getCustomSQLUpdate();
CustomSQL getCustomSQLDelete();
CustomSQL getCustomSQLDeleteAll();
String getLoaderName();
}

View File

@ -0,0 +1,43 @@
/*
* 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.binding.state;
import org.hibernate.mapping.PropertyGeneration;
/**
* @author Gail Badner
* @todo - We need to get a better split into the states. For example this SimpleAttributeBindingState contains
* state which is only relevant for primary/foreign keys. This should be in a different interface. (HF)
*/
public interface SimpleAttributeBindingState extends AttributeBindingState {
boolean isInsertable();
boolean isUpdatable();
boolean isKeyCascadeDeleteEnabled();
String getUnsavedValue();
public PropertyGeneration getPropertyGeneration();
}

View File

@ -35,11 +35,11 @@ import java.util.Set;
*
* @author Steve Ebersole
*/
public abstract class AbstractAttributeContainer implements AttributeContainer, Hierarchical {
public abstract class AbstractAttributeContainer implements AttributeContainer, Hierarchical {
private final String name;
private final Hierarchical superType;
private LinkedHashSet<Attribute> attributeSet = new LinkedHashSet<Attribute>();
private HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>();
private HashMap<String, Attribute> attributeMap = new HashMap<String, Attribute>();
public AbstractAttributeContainer(String name, Hierarchical superType) {
this.name = name;
@ -108,6 +108,16 @@ public abstract class AbstractAttributeContainer implements AttributeContainer,
return attribute;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "AbstractAttributeContainer" );
sb.append( "{name='" ).append( name ).append( '\'' );
sb.append( ", superType=" ).append( superType );
sb.append( '}' );
return sb.toString();
}
protected void addAttribute(Attribute attribute) {
// todo : how to best "secure" this?
if ( attributeMap.put( attribute.getName(), attribute ) != null ) {
@ -121,15 +131,27 @@ public abstract class AbstractAttributeContainer implements AttributeContainer,
public static class SingularAttributeImpl implements SingularAttribute {
private final AttributeContainer attributeContainer;
private final String name;
private Type type;
public SingularAttributeImpl(String name, AttributeContainer attributeContainer) {
this.name = name;
this.attributeContainer = attributeContainer;
}
boolean isTypeResolved() {
return type != null;
}
void resolveType(Type type) {
if ( type == null ) {
throw new IllegalArgumentException( "Attempt to resolve with null type" );
}
this.type = type;
}
@Override
public Type getSingularAttributeType() {
return null;
return type;
}
@Override
@ -152,10 +174,11 @@ public abstract class AbstractAttributeContainer implements AttributeContainer,
private final AttributeContainer attributeContainer;
private final PluralAttributeNature nature;
private final String name;
private String nodeName;
private Type elementType;
public PluralAttributeImpl(String name, PluralAttributeNature nature, AttributeContainer attributeContainer) {
public PluralAttributeImpl(String name, PluralAttributeNature nature, AttributeContainer attributeContainer) {
this.name = name;
this.nature = nature;
this.attributeContainer = attributeContainer;

View File

@ -42,5 +42,4 @@ public interface Type {
* @return persistence type
*/
public TypeNature getNature();
}

View File

@ -23,10 +23,7 @@
*/
package org.hibernate.metamodel.relational;
import java.util.Set;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.state.relational.ColumnRelationalState;
import org.hibernate.metamodel.relational.state.ColumnRelationalState;
/**
* Models a physical column

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.relational;
package org.hibernate.metamodel.relational.state;
import java.util.Set;
@ -33,16 +33,28 @@ import org.hibernate.metamodel.relational.Size;
*/
public interface ColumnRelationalState extends SimpleValueRelationalState {
NamingStrategy getNamingStrategy();
String getExplicitColumnName();
boolean isUnique();
Size getSize();
boolean isNullable();
String getCheckCondition();
String getDefault();
String getSqlType();
String getCustomWriteFragment();
String getCustomReadFragment();
String getComment();
Set<String> getUniqueKeys();
Set<String> getIndexes();
}

View File

@ -21,16 +21,10 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.relational;
import org.hibernate.metamodel.relational.SimpleValue;
package org.hibernate.metamodel.relational.state;
/**
* Created by IntelliJ IDEA.
* User: gbadner
* Date: 5/9/11
* Time: 2:15 PM
* To change this template use File | Settings | File Templates.
* @author Gail Badner
*/
public interface DerivedValueRelationalState extends SimpleValueRelationalState {
String getFormula();

View File

@ -21,12 +21,15 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.relational;
package org.hibernate.metamodel.relational.state;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
/**
* @author Gail Badner
*/
public interface ManyToOneRelationalState extends ValueRelationalState {
boolean isLogicalOneToOne();
String getForeignKeyName();
}

View File

@ -21,7 +21,9 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.relational;
package org.hibernate.metamodel.relational.state;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
/**
* @author Gail Badner

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.relational;
package org.hibernate.metamodel.relational.state;
import java.util.List;

View File

@ -21,19 +21,20 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.relational;
package org.hibernate.metamodel.relational.state;
import org.hibernate.MappingException;
import org.hibernate.metamodel.state.relational.ColumnRelationalState;
import org.hibernate.metamodel.state.relational.DerivedValueRelationalState;
import org.hibernate.metamodel.state.relational.ValueRelationalState;
import org.hibernate.metamodel.state.relational.SimpleValueRelationalState;
import org.hibernate.metamodel.state.relational.TupleRelationalState;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.DerivedValue;
import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.relational.Tuple;
import org.hibernate.metamodel.relational.Value;
/**
* @author Gail Badner
*/
public class ValueFactory {
public class ValueCreator {
public static Column createColumn(TableSpecification table,
String attributeName,
@ -58,7 +59,7 @@ public class ValueFactory {
return value;
}
public static DerivedValue createDerivedValue(TableSpecification table,
public static DerivedValue createDerivedValue(TableSpecification table,
DerivedValueRelationalState state) {
return table.createDerivedValue( state.getFormula() );
}
@ -68,7 +69,7 @@ public class ValueFactory {
SimpleValueRelationalState state,
boolean forceNonNullable,
boolean forceUnique
) {
) {
if ( state instanceof ColumnRelationalState ) {
ColumnRelationalState columnRelationalState = ColumnRelationalState.class.cast( state );
return createColumn( table, attributeName, columnRelationalState, forceNonNullable, forceUnique );
@ -87,7 +88,7 @@ public class ValueFactory {
boolean forceNonNullable,
boolean forceUnique
) {
Tuple tuple = table.createTuple( "[" + attributeName + "]" );
Tuple tuple = table.createTuple( "[" + attributeName + "]" );
for ( SimpleValueRelationalState valueState : state.getRelationalStates() ) {
tuple.addValue( createSimpleValue( table, attributeName, valueState, forceNonNullable, forceUnique ) );
}
@ -101,7 +102,7 @@ public class ValueFactory {
boolean forceUnique) {
Value value = null;
if ( SimpleValueRelationalState.class.isInstance( state ) ) {
value = createSimpleValue(
value = createSimpleValue(
table,
attributeName,
SimpleValueRelationalState.class.cast( state ),

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.relational;
package org.hibernate.metamodel.relational.state;
/**
* @author Gail Badner

View File

@ -23,13 +23,15 @@
*/
package org.hibernate.metamodel.source.annotations;
import java.util.Iterator;
import java.util.Set;
import org.jboss.jandex.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.metamodel.source.annotations.entity.ConfiguredClass;
import org.hibernate.metamodel.source.annotations.entity.ConfiguredClassHierarchy;
import org.hibernate.metamodel.source.annotations.entity.EntityBinder;
import org.hibernate.metamodel.source.annotations.global.FetchProfileBinder;
import org.hibernate.metamodel.source.annotations.global.TableBinder;
import org.hibernate.metamodel.source.annotations.util.ConfiguredClassHierarchyBuilder;
@ -41,36 +43,37 @@ import org.hibernate.metamodel.source.internal.MetadataImpl;
* are added to the annotation index.
*
* @author Hardy Ferentschik
* @todo On top of the index we probably needs to pass some sort of XMLContext for global configuration data
* @todo The annotation index should really be passed at construction time
*/
public class AnnotationBinder {
private static final Logger log = LoggerFactory.getLogger( AnnotationBinder.class );
private final MetadataImpl metadata;
private final Index index;
public AnnotationBinder(MetadataImpl metadata) {
public AnnotationBinder(MetadataImpl metadata, Index index) {
this.metadata = metadata;
this.index = index;
}
public void bind(Index annotationIndex) {
preEntityBindings( annotationIndex );
bindMappedClasses( annotationIndex );
postEntityBindings( annotationIndex );
public void bind() {
preEntityBindings();
bindMappedClasses();
postEntityBindings();
}
/**
* Binds global configuration data prior to entity binding. This includes generators and type definitions
*
* @param annotationIndex the annotation repository/index
* Binds global configuration data prior to entity binding. This includes generators and type definitions.
*/
private void preEntityBindings(Index annotationIndex) {
FetchProfileBinder.bind( metadata, annotationIndex );
private void preEntityBindings() {
FetchProfileBinder.bind( metadata, index );
}
private void bindMappedClasses(Index annotationIndex) {
/**
* Does the actual entity binding (see {@link org.hibernate.metamodel.binding.EntityBinding}.
*/
private void bindMappedClasses() {
// need to order our annotated entities into an order we can process
Set<ConfiguredClassHierarchy> hierarchies = ConfiguredClassHierarchyBuilder.createEntityHierarchies(
annotationIndex, metadata.getServiceRegistry()
index, metadata.getServiceRegistry()
);
// now we process each hierarchy one at the time
@ -86,11 +89,9 @@ public class AnnotationBinder {
/**
* Binds global configuration data post entity binding. This includes mappings which live outside of the configuration for a single
* entity or entity hierarchy, for example sequence generators, fetch profiles, etc
*
* @param annotationIndex the annotation repository/index
*/
private void postEntityBindings(Index annotationIndex) {
TableBinder.bind( metadata, annotationIndex );
private void postEntityBindings() {
TableBinder.bind( metadata, index );
}
}

View File

@ -1,186 +0,0 @@
/*
* 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.annotations;
import java.util.List;
import java.util.Map;
import javax.persistence.DiscriminatorType;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.metamodel.source.annotations.util.JandexHelper;
/**
* Represent a mapped attribute (explicitly or implicitly mapped). Also used for synthetic attributes likes a
* discriminator column.
*
* @author Hardy Ferentschik
*/
public class MappedAttribute implements Comparable<MappedAttribute> {
private final String name;
private final Class<?> type;
private final Map<DotName, List<AnnotationInstance>> annotations;
private final ColumnValues columnValues;
private final boolean isId;
private final boolean isVersioned;
private final boolean isDiscriminator;
static MappedAttribute createMappedAttribute(String name, Class<?> type, Map<DotName, List<AnnotationInstance>> annotations) {
return new MappedAttribute( name, type, annotations, false );
}
static MappedAttribute createDiscriminatorAttribute(Map<DotName, List<AnnotationInstance>> annotations) {
Map<DotName, List<AnnotationInstance>> discriminatorAnnotations = JandexHelper.filterAnnotations(
annotations,
JPADotNames.DISCRIMINATOR_COLUMN,
JPADotNames.DISCRIMINATOR_VALUE,
HibernateDotNames.DISCRIMINATOR_FORMULA,
HibernateDotNames.DISCRIMINATOR_OPTIONS
);
AnnotationInstance discriminatorOptionsAnnotation = JandexHelper.getSingleAnnotation(
annotations, JPADotNames.DISCRIMINATOR_COLUMN
);
String name = DiscriminatorColumnValues.DEFAULT_DISCRIMINATOR_COLUMN_NAME;
Class<?> type = String.class; // string is the discriminator default
if ( discriminatorOptionsAnnotation != null ) {
name = discriminatorOptionsAnnotation.value( "name" ).asString();
DiscriminatorType discriminatorType = Enum.valueOf(
DiscriminatorType.class, discriminatorOptionsAnnotation.value( "discriminatorType" ).asEnum()
);
switch ( discriminatorType ) {
case STRING: {
type = String.class;
break;
}
case CHAR: {
type = Character.class;
break;
}
case INTEGER: {
type = Integer.class;
break;
}
default: {
throw new AnnotationException( "Unsupported discriminator type: " + discriminatorType );
}
}
}
return new MappedAttribute( name, type, discriminatorAnnotations, true );
}
private MappedAttribute(String name, Class<?> type, Map<DotName, List<AnnotationInstance>> annotations, boolean isDiscriminator) {
this.name = name;
this.type = type;
this.annotations = annotations;
this.isDiscriminator = isDiscriminator;
AnnotationInstance idAnnotation = JandexHelper.getSingleAnnotation( annotations, JPADotNames.ID );
isId = idAnnotation != null;
AnnotationInstance versionAnnotation = JandexHelper.getSingleAnnotation( annotations, JPADotNames.VERSION );
isVersioned = versionAnnotation != null;
if ( isDiscriminator ) {
columnValues = new DiscriminatorColumnValues( annotations );
}
else {
AnnotationInstance columnAnnotation = JandexHelper.getSingleAnnotation( annotations, JPADotNames.COLUMN );
columnValues = new ColumnValues( columnAnnotation );
}
if ( isId ) {
// an id must be unique and cannot be nullable
columnValues.setUnique( true );
columnValues.setNullable( false );
}
}
public final String getName() {
return name;
}
public final Class<?> getType() {
return type;
}
public final ColumnValues getColumnValues() {
return columnValues;
}
public boolean isId() {
return isId;
}
public boolean isVersioned() {
return isVersioned;
}
public boolean isDiscriminator() {
return isDiscriminator;
}
/**
* Returns the annotation with the specified name or {@code null}
*
* @param annotationDotName The annotation to retrieve/check
*
* @return Returns the annotation with the specified name or {@code null}. Note, since these are the
* annotations defined on a single attribute there can never be more than one.
*/
public final AnnotationInstance annotations(DotName annotationDotName) {
if ( annotations.containsKey( annotationDotName ) ) {
List<AnnotationInstance> instanceList = annotations.get( annotationDotName );
if ( instanceList.size() > 1 ) {
throw new AssertionFailure( "There cannot be more than one @" + annotationDotName.toString() + " annotation per mapped attribute" );
}
return instanceList.get( 0 );
}
else {
return null;
}
}
@Override
public int compareTo(MappedAttribute mappedProperty) {
return name.compareTo( mappedProperty.getName() );
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "MappedProperty" );
sb.append( "{name='" ).append( name ).append( '\'' );
sb.append( ", type=" ).append( type );
sb.append( '}' );
return sb.toString();
}
}

View File

@ -21,14 +21,21 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.domain;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
package org.hibernate.metamodel.source.annotations.entity;
/**
* @author Gail Badner
* @author Hardy Ferentschik
*/
public interface CollectionElementDomainState {
HibernateTypeDescriptor getHibernateTypeDescriptor();
String getNodeName();
public class AssociationAttribute {
private final MappedAttribute mappedAttribute;
public AssociationAttribute(MappedAttribute mappedAttribute) {
this.mappedAttribute = mappedAttribute;
}
public MappedAttribute getMappedAttribute() {
return mappedAttribute;
}
}

View File

@ -21,12 +21,13 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.hibernate.AssertionFailure;
import org.hibernate.metamodel.source.annotations.JPADotNames;
/**
* Container for the properties defined by {@code @Column}.

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
@ -52,6 +52,7 @@ import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.metamodel.binding.InheritanceType;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.util.JandexHelper;
import org.hibernate.metamodel.source.annotations.util.ReflectionHelper;
import org.hibernate.service.ServiceRegistry;
@ -379,7 +380,7 @@ public class ConfiguredClass {
final Map<DotName, List<AnnotationInstance>> annotations = JandexHelper.getMemberAnnotations(
classInfo, member.getName()
);
return MappedAttribute.createMappedAttribute( name, (Class) type, annotations );
return MappedAttribute.createMappedAttribute( name, ( (Class) type ).getName(), annotations );
}
private Type findResolvedType(String name, ResolvedMember[] resolvedMembers) {

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
import java.util.ArrayList;
import java.util.Iterator;
@ -36,6 +36,7 @@ import org.jboss.jandex.MethodInfo;
import org.hibernate.AnnotationException;
import org.hibernate.metamodel.binding.InheritanceType;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.util.JandexHelper;
import org.hibernate.metamodel.source.annotations.util.ReflectionHelper;
import org.hibernate.service.ServiceRegistry;
@ -195,7 +196,7 @@ public class ConfiguredClassHierarchy implements Iterable<ConfiguredClass> {
private AccessType throwIdNotFoundAnnotationException(List<ClassInfo> classes) {
StringBuilder builder = new StringBuilder();
builder.append( "Unable to determine identifier attribute for class hierarchy " );
builder.append( "Unable to determine identifier attribute for class hierarchy consisting of the classe(s) " );
builder.append( hierarchyListString( classes ) );
throw new AnnotationException( builder.toString() );
}

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
/**
* @author Hardy Ferentschik

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
import java.util.List;
import java.util.Map;
@ -29,6 +29,8 @@ import java.util.Map;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.hibernate.metamodel.source.annotations.HibernateDotNames;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.util.JandexHelper;
/**

View File

@ -21,10 +21,14 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
import java.util.List;
import java.util.Map;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.DotName;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
@ -33,19 +37,22 @@ import org.hibernate.annotations.OptimisticLockType;
import org.hibernate.annotations.PolymorphismType;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.metamodel.binding.Caching;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.binding.state.SimpleAttributeBindingState;
import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.Hierarchical;
import org.hibernate.metamodel.relational.Identifier;
import org.hibernate.metamodel.relational.Schema;
import org.hibernate.metamodel.source.annotations.state.domain.AttributeDomainState;
import org.hibernate.metamodel.source.annotations.state.relational.AttributeColumnRelationalState;
import org.hibernate.metamodel.source.annotations.state.relational.AttributeTupleRelationalState;
import org.hibernate.metamodel.source.annotations.HibernateDotNames;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.entity.state.binding.AttributeBindingStateImpl;
import org.hibernate.metamodel.source.annotations.entity.state.binding.DiscriminatorBindingStateImpl;
import org.hibernate.metamodel.source.annotations.entity.state.relational.ColumnRelationalStateImpl;
import org.hibernate.metamodel.source.annotations.entity.state.relational.TupleRelationalStateImpl;
import org.hibernate.metamodel.source.annotations.util.JandexHelper;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import org.hibernate.service.classloading.spi.ClassLoaderService;
/**
@ -55,11 +62,11 @@ import org.hibernate.service.classloading.spi.ClassLoaderService;
*/
public class EntityBinder {
private final ConfiguredClass configuredClass;
private final MetadataImpl meta;
private final MetadataImplementor meta;
private Schema.Name schemaName;
public EntityBinder(MetadataImpl metadata, ConfiguredClass configuredClass) {
public EntityBinder(MetadataImplementor metadata, ConfiguredClass configuredClass) {
this.configuredClass = configuredClass;
this.meta = metadata;
}
@ -81,11 +88,13 @@ public class EntityBinder {
bindJpaCaching( entityBinding );
bindHibernateCaching( entityBinding );
// take care of the id, attributes and relations
if ( configuredClass.isRoot() ) {
bindId( entityBinding );
}
bindAttributes( entityBinding );
// last, but not least we register the new EntityBinding with the metadata
meta.addEntity( entityBinding );
}
@ -110,18 +119,19 @@ public class EntityBinder {
}
private void bindDiscriminatorColumn(EntityBinding entityBinding) {
MappedAttribute discriminatorAttribute = MappedAttribute.createDiscriminatorAttribute(
configuredClass.getClassInfo().annotations()
final Map<DotName, List<AnnotationInstance>> typeAnnotations = JandexHelper.getTypeAnnotations(
configuredClass.getClassInfo()
);
MappedAttribute discriminatorAttribute = MappedAttribute.createDiscriminatorAttribute( typeAnnotations );
bindSingleMappedAttribute( entityBinding, discriminatorAttribute );
if ( !( discriminatorAttribute.getColumnValues() instanceof DiscriminatorColumnValues ) ) {
throw new AssertionFailure( "Expected discriminator column values" );
}
// TODO: move this into DiscriminatorBindingState
DiscriminatorColumnValues discriminatorColumnvalues = (DiscriminatorColumnValues) discriminatorAttribute.getColumnValues();
entityBinding.getEntityDiscriminator().setForced( discriminatorColumnvalues.isForced() );
entityBinding.getEntityDiscriminator().setInserted( discriminatorColumnvalues.isIncludedInSql() );
entityBinding.setDiscriminatorValue( discriminatorColumnvalues.getDiscriminatorValue() );
}
@ -186,7 +196,7 @@ public class EntityBinder {
}
Caching caching = null;
switch ( meta.getSharedCacheMode() ) {
switch ( meta.getOptions().getSharedCacheMode() ) {
case ALL: {
caching = createCachingForCacheableAnnotation( entityBinding );
break;
@ -280,7 +290,7 @@ public class EntityBinder {
);
String name;
if ( jpaEntityAnnotation.value( "name" ) == null ) {
name = StringHelper.unqualify( configuredClass.getName() );
name = configuredClass.getName();
}
else {
name = jpaEntityAnnotation.value( "name" ).asString();
@ -294,18 +304,13 @@ public class EntityBinder {
);
String idName = JandexHelper.getPropertyName( idAnnotation.target() );
entityBinding.getEntity().getOrCreateSingularAttribute( idName );
SimpleAttributeBinding idBinding = entityBinding.makeSimplePrimaryKeyAttributeBinding( idName );
MappedAttribute idAttribute = configuredClass.getMappedProperty( idName );
AttributeDomainState domainState = new AttributeDomainState( entityBinding, idAttribute );
idBinding.initialize( domainState );
entityBinding.getEntity().getOrCreateSingularAttribute( idName );
AttributeColumnRelationalState columnRelationsState = new AttributeColumnRelationalState( idAttribute, meta );
AttributeTupleRelationalState relationalState = new AttributeTupleRelationalState();
relationalState.addValueState( columnRelationsState );
idBinding.initializeTupleValue( relationalState );
SimpleAttributeBinding attributeBinding = entityBinding.makeSimpleIdAttributeBinding( idName );
attributeBinding.initialize( new AttributeBindingStateImpl( idAttribute ) );
attributeBinding.initialize( new ColumnRelationalStateImpl( idAttribute, meta ) );
}
private void bindAttributes(EntityBinding entityBinding) {
@ -322,27 +327,32 @@ public class EntityBinder {
String attributeName = mappedAttribute.getName();
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName );
SimpleAttributeBinding attributeBinding;
SimpleAttributeBindingState bindingState;
if ( mappedAttribute.isVersioned() ) {
attributeBinding = entityBinding.makeVersionBinding( attributeName );
if ( mappedAttribute.isDiscriminator() ) {
attributeBinding = entityBinding.makeEntityDiscriminator( attributeName ).getValueBinding();
bindingState = new DiscriminatorBindingStateImpl( mappedAttribute );
}
else if ( mappedAttribute.isDiscriminator() ) {
attributeBinding = entityBinding.makeEntityDiscriminatorBinding( attributeName );
else if ( mappedAttribute.isVersioned() ) {
attributeBinding = entityBinding.makeVersionBinding( attributeName );
bindingState = new AttributeBindingStateImpl( mappedAttribute );
}
else {
attributeBinding = entityBinding.makeSimpleAttributeBinding( attributeName );
bindingState = new AttributeBindingStateImpl( mappedAttribute );
}
AttributeDomainState domainState = new AttributeDomainState( entityBinding, mappedAttribute );
attributeBinding.initialize( domainState );
attributeBinding.initialize( bindingState );
if ( configuredClass.hasOwnTable() ) {
AttributeColumnRelationalState columnRelationsState = new AttributeColumnRelationalState(
ColumnRelationalStateImpl columnRelationsState = new ColumnRelationalStateImpl(
mappedAttribute, meta
);
AttributeTupleRelationalState relationalState = new AttributeTupleRelationalState();
TupleRelationalStateImpl relationalState = new TupleRelationalStateImpl();
relationalState.addValueState( columnRelationsState );
attributeBinding.initializeTupleValue( relationalState );
// TODO: if this really just binds a column, then it can be changed to
// attributeBinding.initialize( columnRelationsState );
attributeBinding.initialize( relationalState );
}
}
@ -417,7 +427,7 @@ public class EntityBinder {
return null;
}
EntityBinding parentBinding = meta.getEntityBinding( parent.getSimpleName() );
EntityBinding parentBinding = meta.getEntityBinding( parent.getName() );
if ( parentBinding == null ) {
throw new AssertionFailure(
"Parent entity " + parent.getName() + " of entity " + configuredClass.getName() + " not yet created!"

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations;
package org.hibernate.metamodel.source.annotations.entity;
/**
* An emum for the type of id configuration for an entity.

View File

@ -0,0 +1,347 @@
/*
* 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.annotations.entity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.DiscriminatorType;
import javax.persistence.FetchType;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.DotName;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.source.annotations.HibernateDotNames;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.util.JandexHelper;
/**
* Represent a mapped attribute (explicitly or implicitly mapped). Also used for synthetic attributes like a
* discriminator column.
*
* @author Hardy Ferentschik
*/
public class MappedAttribute implements Comparable<MappedAttribute> {
/**
* Annotations defined on the attribute, keyed against the annotation dot name.
*/
private final Map<DotName, List<AnnotationInstance>> annotations;
/**
* The property name.
*/
private final String name;
/**
* The property type as string.
*/
private final String type;
/**
* Optional type parameters for custom types.
*/
private final Map<String, String> typeParameters;
/**
* Is this property an id property (or part thereof).
*/
private final boolean isId;
/**
* Is this a versioned property (annotated w/ {@code @Version}.
*/
private final boolean isVersioned;
/**
* Is this property a discriminator property.
*/
private final boolean isDiscriminator;
/**
* Whether a change of the property's value triggers a version increment of the entity (in case of optimistic
* locking).
*/
private final boolean isOptimisticLockable;
/**
* Is this property lazy loaded (see {@link javax.persistence.Basic}).
*/
private boolean isLazy = false;
/**
* Is this property optional (see {@link javax.persistence.Basic}).
*/
private boolean isOptional = true;
private PropertyGeneration propertyGeneration;
private boolean isInsertable = true;
private boolean isUpdatable = true;
/**
* Defines the column values (relational values) for this property.
*/
private final ColumnValues columnValues;
static MappedAttribute createMappedAttribute(String name, String type, Map<DotName, List<AnnotationInstance>> annotations) {
return new MappedAttribute( name, type, annotations, false );
}
static MappedAttribute createDiscriminatorAttribute(Map<DotName, List<AnnotationInstance>> annotations) {
AnnotationInstance discriminatorOptionsAnnotation = JandexHelper.getSingleAnnotation(
annotations, JPADotNames.DISCRIMINATOR_COLUMN
);
String name = DiscriminatorColumnValues.DEFAULT_DISCRIMINATOR_COLUMN_NAME;
String type = String.class.toString(); // string is the discriminator default
if ( discriminatorOptionsAnnotation != null ) {
name = discriminatorOptionsAnnotation.value( "name" ).asString();
DiscriminatorType discriminatorType = Enum.valueOf(
DiscriminatorType.class, discriminatorOptionsAnnotation.value( "discriminatorType" ).asEnum()
);
switch ( discriminatorType ) {
case STRING: {
type = String.class.toString();
break;
}
case CHAR: {
type = Character.class.toString();
break;
}
case INTEGER: {
type = Integer.class.toString();
break;
}
default: {
throw new AnnotationException( "Unsupported discriminator type: " + discriminatorType );
}
}
}
return new MappedAttribute( name, type, annotations, true );
}
private MappedAttribute(String name, String type, Map<DotName, List<AnnotationInstance>> annotations, boolean isDiscriminator) {
this.name = name;
this.annotations = annotations;
this.isDiscriminator = isDiscriminator;
this.typeParameters = new HashMap<String, String>();
this.type = determineType( type, typeParameters );
AnnotationInstance idAnnotation = JandexHelper.getSingleAnnotation( annotations, JPADotNames.ID );
isId = idAnnotation != null;
AnnotationInstance versionAnnotation = JandexHelper.getSingleAnnotation( annotations, JPADotNames.VERSION );
isVersioned = versionAnnotation != null;
if ( isDiscriminator ) {
columnValues = new DiscriminatorColumnValues( annotations );
}
else {
AnnotationInstance columnAnnotation = JandexHelper.getSingleAnnotation( annotations, JPADotNames.COLUMN );
columnValues = new ColumnValues( columnAnnotation );
}
if ( isId ) {
// an id must be unique and cannot be nullable
columnValues.setUnique( true );
columnValues.setNullable( false );
}
this.isOptimisticLockable = checkOptimisticLockAnnotation();
checkBasicAnnotation();
checkGeneratedAnnotation();
}
public final String getName() {
return name;
}
public final String getType() {
return type;
}
public final ColumnValues getColumnValues() {
return columnValues;
}
public Map<String, String> getTypeParameters() {
return typeParameters;
}
public boolean isId() {
return isId;
}
public boolean isVersioned() {
return isVersioned;
}
public boolean isDiscriminator() {
return isDiscriminator;
}
public boolean isLazy() {
return isLazy;
}
public boolean isOptional() {
return isOptional;
}
public boolean isInsertable() {
return isInsertable;
}
public boolean isUpdatable() {
return isUpdatable;
}
public PropertyGeneration getPropertyGeneration() {
return propertyGeneration;
}
public boolean isOptimisticLockable() {
return isOptimisticLockable;
}
/**
* Returns the annotation with the specified name or {@code null}
*
* @param annotationDotName The annotation to retrieve/check
*
* @return Returns the annotation with the specified name or {@code null}. Note, since these are the
* annotations defined on a single attribute there can never be more than one.
*/
public final AnnotationInstance getIfExists(DotName annotationDotName) {
if ( annotations.containsKey( annotationDotName ) ) {
List<AnnotationInstance> instanceList = annotations.get( annotationDotName );
if ( instanceList.size() > 1 ) {
throw new AssertionFailure( "There cannot be more than one @" + annotationDotName.toString() + " annotation per mapped attribute" );
}
return instanceList.get( 0 );
}
else {
return null;
}
}
@Override
public int compareTo(MappedAttribute mappedProperty) {
return name.compareTo( mappedProperty.getName() );
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "MappedAttribute" );
sb.append( "{name='" ).append( name ).append( '\'' );
sb.append( ", type='" ).append( type ).append( '\'' );
sb.append( ", isId=" ).append( isId );
sb.append( ", isVersioned=" ).append( isVersioned );
sb.append( ", isDiscriminator=" ).append( isDiscriminator );
sb.append( '}' );
return sb.toString();
}
/**
* We need to check whether the is an explicit type specified via {@link org.hibernate.annotations.Type}.
*
* @param type the type specified via the constructor
* @param typeParameters map for type parameters in case there are any
*
* @return the final type for this mapped attribute
*/
private String determineType(String type, Map<String, String> typeParameters) {
AnnotationInstance typeAnnotation = getIfExists( HibernateDotNames.TYPE );
if ( typeAnnotation == null ) {
// return discovered type
return type;
}
AnnotationValue parameterAnnotationValue = typeAnnotation.value( "parameters" );
if ( parameterAnnotationValue != null ) {
AnnotationInstance[] parameterAnnotations = parameterAnnotationValue.asNestedArray();
for ( AnnotationInstance parameterAnnotationInstance : parameterAnnotations ) {
typeParameters.put(
parameterAnnotationInstance.value( "name" ).asString(),
parameterAnnotationInstance.value( "value" ).asString()
);
}
}
return typeAnnotation.value( "type" ).asString();
}
private boolean checkOptimisticLockAnnotation() {
boolean triggersVersionIncrement = true;
AnnotationInstance optimisticLockAnnotation = getIfExists( HibernateDotNames.OPTIMISTIC_LOCK );
if ( optimisticLockAnnotation != null ) {
boolean exclude = optimisticLockAnnotation.value( "excluded" ).asBoolean();
triggersVersionIncrement = !exclude;
}
return triggersVersionIncrement;
}
private void checkBasicAnnotation() {
AnnotationInstance basicAnnotation = getIfExists( JPADotNames.BASIC );
if ( basicAnnotation != null ) {
FetchType fetchType = FetchType.LAZY;
AnnotationValue fetchValue = basicAnnotation.value( "fetch" );
if ( fetchValue != null ) {
fetchType = Enum.valueOf( FetchType.class, fetchValue.asEnum() );
}
this.isLazy = fetchType == FetchType.LAZY;
AnnotationValue optionalValue = basicAnnotation.value( "optional" );
if ( optionalValue != null ) {
this.isOptional = optionalValue.asBoolean();
}
}
}
// TODO - there is more todo for updatable and insertable. Checking the @Generated annotation is only one part (HF)
private void checkGeneratedAnnotation() {
AnnotationInstance generatedAnnotation = getIfExists( HibernateDotNames.GENERATED );
if ( generatedAnnotation != null ) {
this.isInsertable = false;
AnnotationValue generationTimeValue = generatedAnnotation.value();
if ( generationTimeValue != null ) {
GenerationTime genTime = Enum.valueOf( GenerationTime.class, generationTimeValue.asEnum() );
if ( GenerationTime.ALWAYS.equals( genTime ) ) {
this.isUpdatable = false;
this.propertyGeneration = PropertyGeneration.parse( genTime.toString().toLowerCase() );
}
}
}
}
}

View File

@ -0,0 +1,30 @@
/*
* 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.annotations.entity;
/**
* This package contains binding code for entities. In particular it contains classes like {@code ConfiguredClass} and
* {@code MappedAttribute} which are populated from annotations to make it easier to bind to the Hibernate metamodel.
* The configured classes (entities) are also ordered in a ways that they can be bound in the right order.
*/

View File

@ -0,0 +1,122 @@
/*
* 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.annotations.entity.state.binding;
import java.util.Map;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.binding.state.SimpleAttributeBindingState;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.annotations.entity.MappedAttribute;
/**
* Implementation of the attribute binding state via annotation configuration.
*
* @author Hardy Ferentschik
* @todo in the end we can maybe just let MappedAttribute implement SimpleAttributeBindingState. (HF)
*/
public class AttributeBindingStateImpl implements SimpleAttributeBindingState {
private final MappedAttribute mappedAttribute;
public AttributeBindingStateImpl(MappedAttribute mappedAttribute) {
this.mappedAttribute = mappedAttribute;
}
@Override
public String getAttributeName() {
return mappedAttribute.getName();
}
@Override
public PropertyGeneration getPropertyGeneration() {
return mappedAttribute.getPropertyGeneration();
}
@Override
public boolean isInsertable() {
return mappedAttribute.isInsertable();
}
@Override
public boolean isUpdatable() {
return mappedAttribute.isUpdatable();
}
@Override
public String getTypeName() {
return mappedAttribute.getType();
}
@Override
public Map<String, String> getTypeParameters() {
return mappedAttribute.getTypeParameters();
}
@Override
public boolean isLazy() {
return mappedAttribute.isLazy();
}
@Override
public boolean isOptimisticLockable() {
return mappedAttribute.isOptimisticLockable();
}
@Override
public boolean isKeyCascadeDeleteEnabled() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getUnsavedValue() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getPropertyAccessorName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isAlternateUniqueKey() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getCascade() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getNodeName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Map<String, MetaAttribute> getMetaAttributes() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -21,30 +21,35 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.hbm.state.domain;
package org.hibernate.metamodel.source.annotations.entity.state.binding;
import org.hibernate.metamodel.binding.CollectionElement;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLElementElement;
import org.hibernate.metamodel.state.domain.CollectionElementDomainState;
import org.hibernate.metamodel.source.annotations.entity.DiscriminatorColumnValues;
import org.hibernate.metamodel.source.annotations.entity.MappedAttribute;
/**
* @author Gail Badner
*
* TODO: extract a superclass that sets defaults for other stuff
*/
public class HbmCollectionElementDomainState implements CollectionElementDomainState {
private final XMLElementElement element;
public class DiscriminatorBindingStateImpl
extends AttributeBindingStateImpl implements org.hibernate.metamodel.binding.state.DiscriminatorBindingState {
private final boolean isForced;
private final boolean isInserted;
HbmCollectionElementDomainState(XMLElementElement element) {
this.element = element;
public DiscriminatorBindingStateImpl(MappedAttribute mappedAttribute) {
super( mappedAttribute );
DiscriminatorColumnValues columnValues = DiscriminatorColumnValues.class.cast( mappedAttribute.getColumnValues() );
isForced = columnValues.isForced();
isInserted = columnValues.isIncludedInSql();
}
public final HibernateTypeDescriptor getHibernateTypeDescriptor() {
HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
hibernateTypeDescriptor.setTypeName( element.getTypeAttribute() );
return hibernateTypeDescriptor;
@Override
public boolean isForced() {
return isForced;
}
public final String getNodeName() {
return element.getNode();
@Override
public boolean isInsertable() {
return isInserted;
}
}

View File

@ -0,0 +1,58 @@
/*
* 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.annotations.entity.state.binding;
import org.hibernate.metamodel.binding.state.ManyToOneAttributeBindingState;
import org.hibernate.metamodel.source.annotations.entity.AssociationAttribute;
/**
* @author Hardy Ferentschik
*/
public class ManyToOneBindingStateImpl extends AttributeBindingStateImpl implements ManyToOneAttributeBindingState {
public ManyToOneBindingStateImpl(AssociationAttribute associationAttribute) {
super( associationAttribute.getMappedAttribute() );
}
@Override
public boolean isUnwrapProxy() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getReferencedAttributeName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getReferencedEntityName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean ignoreNotFound() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations.state.relational;
package org.hibernate.metamodel.source.annotations.entity.state.relational;
import java.util.ArrayList;
import java.util.Arrays;
@ -33,18 +33,17 @@ import org.jboss.jandex.AnnotationInstance;
import org.hibernate.AnnotationException;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.Size;
import org.hibernate.metamodel.source.annotations.ColumnValues;
import org.hibernate.metamodel.relational.state.ColumnRelationalState;
import org.hibernate.metamodel.source.annotations.HibernateDotNames;
import org.hibernate.metamodel.source.annotations.MappedAttribute;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.state.relational.ColumnRelationalState;
import org.hibernate.metamodel.source.annotations.entity.ColumnValues;
import org.hibernate.metamodel.source.annotations.entity.MappedAttribute;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
/**
* @author Hardy Ferentschik
*/
public class AttributeColumnRelationalState implements ColumnRelationalState {
public class ColumnRelationalStateImpl implements ColumnRelationalState {
private final NamingStrategy namingStrategy;
private final String columnName;
private final boolean unique;
@ -62,9 +61,9 @@ public class AttributeColumnRelationalState implements ColumnRelationalState {
private Set<String> uniqueKeys = new HashSet<String>();
public AttributeColumnRelationalState(MappedAttribute attribute, MetadataImpl meta) {
public ColumnRelationalStateImpl(MappedAttribute attribute, MetadataImplementor meta) {
ColumnValues columnValues = attribute.getColumnValues();
namingStrategy = meta.getNamingStrategy();
namingStrategy = meta.getOptions().getNamingStrategy();
columnName = columnValues.getName().isEmpty() ? attribute.getName() : columnValues.getName();
unique = columnValues.isUnique();
nullable = columnValues.isNullable();
@ -156,13 +155,13 @@ public class AttributeColumnRelationalState implements ColumnRelationalState {
List<AnnotationInstance> allColumnTransformerAnnotations = new ArrayList<AnnotationInstance>();
// not quite sure about the usefulness of @ColumnTransformers (HF)
AnnotationInstance columnTransformersAnnotations = attribute.annotations( HibernateDotNames.COLUMN_TRANSFORMERS );
AnnotationInstance columnTransformersAnnotations = attribute.getIfExists( HibernateDotNames.COLUMN_TRANSFORMERS );
if ( columnTransformersAnnotations != null ) {
AnnotationInstance[] annotationInstances = allColumnTransformerAnnotations.get( 0 ).value().asNestedArray();
allColumnTransformerAnnotations.addAll( Arrays.asList( annotationInstances ) );
}
AnnotationInstance columnTransformerAnnotation = attribute.annotations( HibernateDotNames.COLUMN_TRANSFORMER );
AnnotationInstance columnTransformerAnnotation = attribute.getIfExists( HibernateDotNames.COLUMN_TRANSFORMER );
if ( columnTransformerAnnotation != null ) {
allColumnTransformerAnnotations.add( columnTransformerAnnotation );
}
@ -197,7 +196,7 @@ public class AttributeColumnRelationalState implements ColumnRelationalState {
private String parseCheckAnnotation(MappedAttribute attribute) {
String checkCondition = null;
AnnotationInstance checkAnnotation = attribute.annotations( HibernateDotNames.CHECK );
AnnotationInstance checkAnnotation = attribute.getIfExists( HibernateDotNames.CHECK );
if ( checkAnnotation != null ) {
checkCondition = checkAnnotation.value( "constraints" ).toString();
}
@ -206,7 +205,7 @@ public class AttributeColumnRelationalState implements ColumnRelationalState {
private Set<String> parseIndexAnnotation(MappedAttribute attribute) {
Set<String> indexNames = new HashSet<String>();
AnnotationInstance indexAnnotation = attribute.annotations( HibernateDotNames.INDEX );
AnnotationInstance indexAnnotation = attribute.getIfExists( HibernateDotNames.INDEX );
if ( indexAnnotation != null ) {
String indexName = indexAnnotation.value( "name" ).toString();
indexNames.add( indexName );

View File

@ -0,0 +1,20 @@
package org.hibernate.metamodel.source.annotations.entity.state.relational;
import org.hibernate.metamodel.relational.state.ManyToOneRelationalState;
/**
* @author Hardy Ferentschik
*/
public class ManyToOneRelationalStateImpl extends TupleRelationalStateImpl implements ManyToOneRelationalState {
@Override
public boolean isLogicalOneToOne() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getForeignKeyName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -21,18 +21,18 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.annotations.state.relational;
package org.hibernate.metamodel.source.annotations.entity.state.relational;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.metamodel.state.relational.SimpleValueRelationalState;
import org.hibernate.metamodel.state.relational.TupleRelationalState;
import org.hibernate.metamodel.relational.state.SimpleValueRelationalState;
import org.hibernate.metamodel.relational.state.TupleRelationalState;
/**
* @author Hardy Ferentschik
*/
public class AttributeTupleRelationalState implements TupleRelationalState {
public class TupleRelationalStateImpl implements TupleRelationalState {
List<SimpleValueRelationalState> valueStates = new ArrayList<SimpleValueRelationalState>();
public void addValueState(SimpleValueRelationalState state) {

View File

@ -24,5 +24,5 @@
package org.hibernate.metamodel.source.annotations;
/**
* This package contains the core binding code for binding annotation based configuration to the Hibernate metadata model.
* This package contains the binding code for binding annotation based configuration to the Hibernate metamodel.
*/

View File

@ -1,109 +0,0 @@
package org.hibernate.metamodel.source.annotations.state.domain;
import java.util.Map;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.state.domain.SimpleAttributeDomainState;
import org.hibernate.metamodel.source.annotations.MappedAttribute;
/**
* @author Hardy Ferentschik
*/
public class AttributeDomainState implements SimpleAttributeDomainState {
private final PropertyGeneration propertyGeneration = null;
private final HibernateTypeDescriptor typeDescriptor;
private final Attribute attribute;
public AttributeDomainState(EntityBinding entityBinding, MappedAttribute mappedAttribute) {
typeDescriptor = new HibernateTypeDescriptor();
typeDescriptor.setTypeName( mappedAttribute.getType().getName() );
Entity entity = entityBinding.getEntity();
attribute = entity.getOrCreateSingularAttribute( mappedAttribute.getName() );
}
@Override
public PropertyGeneration getPropertyGeneration() {
// GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
// String generatorType = generatedValue != null ?
// generatorType( generatedValue.strategy(), mappings ) :
// "assigned";
// String generatorName = generatedValue != null ?
// generatedValue.generator() :
// BinderHelper.ANNOTATION_STRING_DEFAULT;
return propertyGeneration;
}
@Override
public boolean isInsertable() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isUpdateable() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isKeyCasadeDeleteEnabled() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getUnsavedValue() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public HibernateTypeDescriptor getHibernateTypeDescriptor() {
return typeDescriptor;
}
@Override
public Attribute getAttribute() {
return attribute;
}
@Override
public boolean isLazy() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getPropertyAccessorName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isAlternateUniqueKey() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getCascade() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isOptimisticLockable() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getNodeName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Map<String, MetaAttribute> getMetaAttributes() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -36,8 +36,9 @@ import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.hibernate.AnnotationException;
import org.hibernate.metamodel.source.annotations.ConfiguredClassHierarchy;
import org.hibernate.metamodel.source.annotations.entity.ConfiguredClassHierarchy;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.entity.ConfiguredClassHierarchy;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.classloading.spi.ClassLoaderService;

View File

@ -126,20 +126,6 @@ public class JandexHelper {
}
}
/**
* @param annotations List of annotation instances keyed against their dot name.
* @param annotationNames the annotation names to filter
*
* @return a new map of annotation instances only containing annotations of the specified dot names.
*/
public static Map<DotName, List<AnnotationInstance>> filterAnnotations(Map<DotName, List<AnnotationInstance>> annotations, DotName... annotationNames) {
Map<DotName, List<AnnotationInstance>> filteredAnnotations = new HashMap<DotName, List<AnnotationInstance>>();
for ( DotName name : annotationNames ) {
filteredAnnotations.put( name, annotations.get( name ) );
}
return filteredAnnotations;
}
/**
* Creates a jandex index for the specified classes
*
@ -202,6 +188,22 @@ public class JandexHelper {
return annotations;
}
public static Map<DotName, List<AnnotationInstance>> getTypeAnnotations(ClassInfo classInfo) {
if ( classInfo == null ) {
throw new IllegalArgumentException( "classInfo cannot be null" );
}
Map<DotName, List<AnnotationInstance>> annotations = new HashMap<DotName, List<AnnotationInstance>>();
for ( List<AnnotationInstance> annotationList : classInfo.annotations().values() ) {
for ( AnnotationInstance instance : annotationList ) {
if ( instance.target() instanceof ClassInfo ) {
addAnnotationToMap( instance, annotations );
}
}
}
return annotations;
}
private static void addAnnotationToMap(AnnotationInstance instance, Map<DotName, List<AnnotationInstance>> annotations) {
DotName dotName = instance.name();
List<AnnotationInstance> list;

View File

@ -10,8 +10,6 @@ import org.hibernate.metamodel.source.annotations.xml.mocker.EntityMappingsMocke
import org.hibernate.metamodel.source.internal.JaxbRoot;
import org.hibernate.metamodel.source.internal.MetadataImpl;
//import org.hibernate.metamodel.source.util.xml.XmlHelper;
/**
* @author Hardy Ferentschik
* @todo Need some create some XMLContext as well which can be populated w/ information which can not be expressed via annotations
@ -40,9 +38,6 @@ public class OrmXmlParser {
list, annotationIndex, meta.getServiceRegistry()
).mockNewIndex();
}
}

View File

@ -34,18 +34,18 @@ import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.BagBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.ManyToOneAttributeBinding;
import org.hibernate.metamodel.binding.PluralAttributeBinding;
import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.binding.state.ManyToOneAttributeBindingState;
import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.Hierarchical;
import org.hibernate.metamodel.domain.PluralAttributeNature;
import org.hibernate.metamodel.relational.Schema;
import org.hibernate.metamodel.relational.Table;
import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.relational.UniqueKey;
import org.hibernate.metamodel.source.hbm.state.domain.HbmManyToOneAttributeDomainState;
import org.hibernate.metamodel.source.hbm.state.domain.HbmPluralAttributeDomainState;
import org.hibernate.metamodel.source.hbm.state.domain.HbmSimpleAttributeDomainState;
import org.hibernate.metamodel.relational.state.ManyToOneRelationalState;
import org.hibernate.metamodel.source.hbm.state.binding.HbmManyToOneAttributeBindingState;
import org.hibernate.metamodel.source.hbm.state.binding.HbmPluralAttributeBindingState;
import org.hibernate.metamodel.source.hbm.state.binding.HbmSimpleAttributeBindingState;
import org.hibernate.metamodel.source.hbm.state.relational.HbmManyToOneRelationalStateContainer;
import org.hibernate.metamodel.source.hbm.state.relational.HbmSimpleValueRelationalStateContainer;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLAnyElement;
@ -70,7 +70,11 @@ import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlQueryElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSubclassElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLTuplizerElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLUnionSubclassElement;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.binding.state.PluralAttributeBindingState;
import org.hibernate.metamodel.binding.state.SimpleAttributeBindingState;
import org.hibernate.metamodel.relational.state.TupleRelationalState;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
/**
* TODO : javadoc
@ -102,7 +106,7 @@ abstract class AbstractEntityBinder {
return hibernateMappingBinder.getHibernateXmlBinder();
}
protected MetadataImpl getMetadata() {
protected MetadataImplementor getMetadata() {
return hibernateMappingBinder.getHibernateXmlBinder().getMetadata();
}
@ -111,7 +115,7 @@ abstract class AbstractEntityBinder {
}
protected NamingStrategy getNamingStrategy() {
return getMetadata().getNamingStrategy();
return getMetadata().getOptions().getNamingStrategy();
}
protected void basicEntityBinding(XMLHibernateMapping.XMLClass entityClazz,
@ -239,12 +243,16 @@ abstract class AbstractEntityBinder {
if ( entityClazz.getTable() == null ) {
logicalTableName = StringHelper.unqualify( entityName );
physicalTableName = getHibernateXmlBinder().getMetadata()
.getOptions()
.getNamingStrategy()
.classToTableName( entityName );
}
else {
logicalTableName = entityClazz.getTable();
physicalTableName = getHibernateXmlBinder().getMetadata().getNamingStrategy().tableName( logicalTableName );
physicalTableName = getHibernateXmlBinder().getMetadata()
.getOptions()
.getNamingStrategy()
.tableName( logicalTableName );
}
// todo : find out the purpose of these logical bindings
// mappings.addTableBinding( schema, catalog, logicalTableName, physicalTableName, denormalizedSuperTable );
@ -284,8 +292,7 @@ abstract class AbstractEntityBinder {
for ( Object attribute : entityClazz.getPropertyOrManyToOneOrOneToOne() ) {
if ( XMLBagElement.class.isInstance( attribute ) ) {
XMLBagElement collection = XMLBagElement.class.cast( attribute );
BagBinding collectionBinding = entityBinding.makeBagAttributeBinding( collection.getName() );
bindBag( collection, collectionBinding, entityBinding );
BagBinding collectionBinding = makeBagAttributeBinding( collection, entityBinding );
hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( collectionBinding );
attributeBinding = collectionBinding;
}
@ -321,12 +328,7 @@ abstract class AbstractEntityBinder {
}
else if ( XMLManyToOneElement.class.isInstance( attribute ) ) {
XMLManyToOneElement manyToOne = XMLManyToOneElement.class.cast( attribute );
ManyToOneAttributeBinding manyToOneBinding = entityBinding.makeManyToOneAttributeBinding( manyToOne.getName() );
bindManyToOne( manyToOne, manyToOneBinding, entityBinding );
attributeBinding = manyToOneBinding;
// todo : implement
// value = new ManyToOne( mappings, table );
// bindManyToOne( subElement, (ManyToOne) value, propertyName, nullable, mappings );
attributeBinding = makeManyToOneAttributeBinding( manyToOne, entityBinding );
}
else if ( XMLAnyElement.class.isInstance( attribute ) ) {
// todo : implement
@ -340,9 +342,7 @@ abstract class AbstractEntityBinder {
}
else if ( XMLPropertyElement.class.isInstance( attribute ) ) {
XMLPropertyElement property = XMLPropertyElement.class.cast( attribute );
SimpleAttributeBinding binding = entityBinding.makeSimpleAttributeBinding( property.getName() );
bindSimpleAttribute( property, binding, entityBinding );
attributeBinding = binding;
attributeBinding = bindProperty( property, entityBinding );
}
else if ( XMLComponentElement.class.isInstance( attribute )
|| XMLDynamicComponentElement.class.isInstance( attribute )
@ -441,200 +441,86 @@ PrimitiveArray
}
protected void bindSimpleAttribute(XMLHibernateMapping.XMLClass.XMLId id,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding,
String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ),
entityBinding.getMetaAttributes(),
id
)
);
}
protected SimpleAttributeBinding bindProperty(XMLPropertyElement property,
EntityBinding entityBinding) {
SimpleAttributeBindingState bindingState = new HbmSimpleAttributeBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
getHibernateMappingBinder(),
entityBinding.getMetaAttributes(),
property
);
if ( attributeBinding.getValue() == null ) {
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
attributeBinding.initializeTupleValue(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
id
)
);
}
// boolean (true here) indicates that by default column names should be guessed
ValueRelationalState relationalState =
convertToSimpleValueRelationalStateIfPossible(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
property
)
);
entityBinding.getEntity().getOrCreateSingularAttribute( bindingState.getAttributeName() );
return entityBinding.makeSimpleAttributeBinding( bindingState.getAttributeName() )
.initialize( bindingState )
.initialize( relationalState );
}
protected void bindSimpleAttribute(XMLHibernateMapping.XMLClass.XMLDiscriminator discriminator,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding,
String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ),
discriminator
)
);
}
if ( attributeBinding.getValue() == null ) {
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
attributeBinding.initializeTupleValue(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
discriminator
)
);
protected static ValueRelationalState convertToSimpleValueRelationalStateIfPossible(ValueRelationalState state) {
// TODO: should a single-valued tuple always be converted???
if ( !TupleRelationalState.class.isInstance( state ) ) {
return state;
}
TupleRelationalState tupleRelationalState = TupleRelationalState.class.cast( state );
return tupleRelationalState.getRelationalStates().size() == 1 ?
tupleRelationalState.getRelationalStates().get( 0 ) :
state;
}
protected void bindSimpleAttribute(XMLHibernateMapping.XMLClass.XMLVersion version,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding,
String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ),
entityBinding.getMetaAttributes(),
version
)
);
}
if ( attributeBinding.getValue() == null ) {
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
attributeBinding.initializeTupleValue(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
version
)
);
}
}
protected void bindSimpleAttribute(XMLHibernateMapping.XMLClass.XMLTimestamp timestamp,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding,
String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ),
entityBinding.getMetaAttributes(),
timestamp
)
);
}
if ( attributeBinding.getValue() == null ) {
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
attributeBinding.initializeTupleValue(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
timestamp
)
);
}
}
protected void bindSimpleAttribute(XMLPropertyElement property,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( property.getName() ),
entityBinding.getMetaAttributes(),
property
)
);
}
if ( attributeBinding.getValue() == null ) {
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
attributeBinding.initializeTupleValue(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
property
)
);
}
}
protected void bindBag(
protected BagBinding makeBagAttributeBinding(
XMLBagElement collection,
PluralAttributeBinding collectionBinding,
EntityBinding entityBinding) {
if ( collectionBinding.getAttribute() == null ) {
// domain model has not been bound yet
collectionBinding.initialize(
new HbmPluralAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
collection,
entityBinding.getMetaAttributes(),
entityBinding.getEntity().getOrCreatePluralAttribute(
collection.getName(),
PluralAttributeNature.BAG
)
)
);
}
if ( collectionBinding.getValue() == null ) {
PluralAttributeBindingState bindingState =
new HbmPluralAttributeBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
hibernateMappingBinder,
collection,
entityBinding.getMetaAttributes()
);
BagBinding collectionBinding = entityBinding.makeBagAttributeBinding( bindingState.getAttributeName() )
.initialize( bindingState );
// todo : relational model binding
}
return collectionBinding;
}
private void bindManyToOne(XMLManyToOneElement manyToOne,
ManyToOneAttributeBinding attributeBinding,
private ManyToOneAttributeBinding makeManyToOneAttributeBinding(XMLManyToOneElement manyToOne,
EntityBinding entityBinding) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmManyToOneAttributeDomainState(
hibernateMappingBinder.getHibernateXmlBinder().getMetadata(),
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( manyToOne.getName() ),
entityBinding.getMetaAttributes(),
manyToOne
)
);
}
ManyToOneAttributeBindingState bindingState =
new HbmManyToOneAttributeBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
hibernateMappingBinder,
entityBinding.getMetaAttributes(),
manyToOne
);
if ( attributeBinding.getValue() == null ) {
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
attributeBinding.initialize(
new HbmManyToOneRelationalStateContainer(
getHibernateMappingBinder(),
true,
manyToOne
)
);
}
// boolean (true here) indicates that by default column names should be guessed
ManyToOneRelationalState relationalState =
new HbmManyToOneRelationalStateContainer(
getHibernateMappingBinder(),
true,
manyToOne
);
entityBinding.getEntity().getOrCreateSingularAttribute( bindingState.getAttributeName() );
ManyToOneAttributeBinding manyToOneAttributeBinding =
entityBinding.makeManyToOneAttributeBinding( bindingState.getAttributeName() )
.initialize( bindingState )
.initialize( relationalState );
return manyToOneAttributeBinding;
}
// private static Property createProperty(

View File

@ -36,7 +36,7 @@ import org.hibernate.metamodel.binding.CustomSQL;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLMetaElement;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
/**
* TODO : javadoc

View File

@ -32,7 +32,6 @@ import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.MetadataSource;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.Origin;
import org.hibernate.metamodel.source.internal.JaxbRoot;
@ -46,12 +45,16 @@ import org.hibernate.metamodel.source.hbm.xml.mapping.XMLQueryElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlQueryElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSubclassElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLUnionSubclassElement;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
import org.hibernate.service.ServiceRegistry;
/**
* Responsible for performing binding of the {@code <hibernate-mapping/>} DOM element
*/
public class HibernateMappingBinder implements MappingDefaults {
private static final String DEFAULT_IDENTIFIER_COLUMN_NAME = "id";
private static final String DEFAULT_DISCRIMINATOR_COLUMN_NAME = "class";
private final HibernateXmlBinder hibernateXmlBinder;
private final JaxbRoot<XMLHibernateMapping> jaxbRoot;
private final XMLHibernateMapping hibernateMapping;
@ -103,6 +106,15 @@ public class HibernateMappingBinder implements MappingDefaults {
return defaultCatalogName;
}
public String getDefaultIdColumnName() {
return DEFAULT_IDENTIFIER_COLUMN_NAME;
}
public String getDefaultDiscriminatorColumnName() {
return DEFAULT_DISCRIMINATOR_COLUMN_NAME;
}
public String getDefaultCascade() {
return defaultCascade;
}
@ -115,8 +127,13 @@ public class HibernateMappingBinder implements MappingDefaults {
return defaultLazy;
}
@Override
public ServiceRegistry getServiceRegistry() {
return hibernateXmlBinder.getMetadata().getServiceRegistry();
}
public NamingStrategy getNamingStrategy() {
return hibernateXmlBinder.getMetadata().getNamingStrategy();
return hibernateXmlBinder.getMetadata().getOptions().getNamingStrategy();
}
public String getPackageName() {

View File

@ -40,8 +40,8 @@ import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.internal.JaxbRoot;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
/**
* Binder for {@code hbm.xml} files
@ -51,14 +51,14 @@ import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping;
public class HibernateXmlBinder {
private static final Logger log = LoggerFactory.getLogger( HibernateXmlBinder.class );
private final MetadataImpl metadata;
private final MetadataImplementor metadata;
private final Map<String, MetaAttribute> globalMetas;
public HibernateXmlBinder(MetadataImpl metadata) {
public HibernateXmlBinder(MetadataImplementor metadata) {
this( metadata, Collections.<String, MetaAttribute>emptyMap() );
}
public HibernateXmlBinder(MetadataImpl metadata, Map<String, MetaAttribute> globalMetas) {
public HibernateXmlBinder(MetadataImplementor metadata, Map<String, MetaAttribute> globalMetas) {
this.metadata = metadata;
this.globalMetas = globalMetas;
}
@ -85,7 +85,7 @@ public class HibernateXmlBinder {
mappingBinder.processHibernateMapping();
}
MetadataImpl getMetadata() {
MetadataImplementor getMetadata() {
return metadata;
}

View File

@ -21,23 +21,37 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.binding;
package org.hibernate.metamodel.source.hbm;
import java.util.Map;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.service.ServiceRegistry;
/**
* @author Gail Badner
*/
public interface MappingDefaults {
Map<String, MetaAttribute> getMappingMetas();
String getPackageName();
String getDefaultSchemaName();
String getDefaultCatalogName();
String getDefaultIdColumnName();
String getDefaultDiscriminatorColumnName();
String getDefaultCascade();
String getDefaultAccess();
boolean isDefaultLazy();
ServiceRegistry getServiceRegistry();
NamingStrategy getNamingStrategy();
}

View File

@ -26,18 +26,22 @@ package org.hibernate.metamodel.source.hbm;
import org.hibernate.InvalidMappingException;
import org.hibernate.MappingException;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.mapping.RootClass;
import org.hibernate.metamodel.binding.Caching;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.binding.state.SimpleAttributeBindingState;
import org.hibernate.metamodel.relational.Identifier;
import org.hibernate.metamodel.relational.InLineView;
import org.hibernate.metamodel.relational.Schema;
import org.hibernate.metamodel.relational.state.ValueRelationalState;
import org.hibernate.metamodel.source.hbm.state.binding.HbmDiscriminatorBindingState;
import org.hibernate.metamodel.source.hbm.state.binding.HbmSimpleAttributeBindingState;
import org.hibernate.metamodel.source.hbm.state.relational.HbmSimpleValueRelationalStateContainer;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLCacheElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLCompositeId;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLId;
import org.hibernate.metamodel.binding.state.DiscriminatorBindingState;
/**
* TODO : javadoc
@ -76,7 +80,7 @@ class RootEntityBinder extends AbstractEntityBinder {
bindIdentifier( xmlClazz, entityBinding );
bindDiscriminator( xmlClazz, entityBinding );
bindVersion( xmlClazz, entityBinding );
bindVersionOrTimestamp( xmlClazz, entityBinding );
bindCaching( xmlClazz, entityBinding );
// called createClassProperties in HBMBinder...
@ -135,18 +139,25 @@ class RootEntityBinder extends AbstractEntityBinder {
}
private void bindSimpleId(XMLId id, EntityBinding entityBinding) {
// Handle the domain portion of the binding...
final String explicitName = id.getName();
final String attributeName = explicitName == null ? RootClass.DEFAULT_IDENTIFIER_COLUMN_NAME : explicitName;
SimpleAttributeBinding idBinding = entityBinding.makeSimplePrimaryKeyAttributeBinding( attributeName );
bindSimpleAttribute( id, idBinding, entityBinding, attributeName );
if ( !Column.class.isInstance( idBinding.getValue() ) ) {
// this should never ever happen..
throw new MappingException( "Unanticipated situation" );
SimpleAttributeBindingState bindingState = new HbmSimpleAttributeBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
getHibernateMappingBinder(),
entityBinding.getMetaAttributes(),
id
);
// boolean (true here) indicates that by default column names should be guessed
HbmSimpleValueRelationalStateContainer relationalStateContainer = new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(), true, id
);
if ( relationalStateContainer.getRelationalStates().size() > 1 ) {
throw new MappingException( "ID is expected to be a single column, but has more than 1 value" );
}
entityBinding.getBaseTable().getPrimaryKey().addColumn( Column.class.cast( idBinding.getValue() ) );
entityBinding.getEntity().getOrCreateSingularAttribute( bindingState.getAttributeName() );
entityBinding.makeSimpleIdAttributeBinding( bindingState.getAttributeName() )
.initialize( bindingState )
.initialize( relationalStateContainer.getRelationalStates().get( 0 ) );
// if ( propertyName == null || entity.getPojoRepresentation() == null ) {
// bindSimpleValue( idNode, id, false, RootClass.DEFAULT_IDENTIFIER_COLUMN_NAME, mappings );
// if ( !id.isTypeSpecified() ) {
@ -233,53 +244,97 @@ class RootEntityBinder extends AbstractEntityBinder {
return;
}
// Discriminator.getName() is not defined, so the attribute will always be RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME
SimpleAttributeBinding discriminatorBinding = entityBinding.makeEntityDiscriminatorBinding( RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME );
// Handle the relational portion of the binding...
bindSimpleAttribute(
xmlEntityClazz.getDiscriminator(),
discriminatorBinding,
entityBinding,
RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME
DiscriminatorBindingState bindingState = new HbmDiscriminatorBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
getHibernateMappingBinder(),
xmlEntityClazz.getDiscriminator()
);
entityBinding.getEntityDiscriminator().setForced( xmlEntityClazz.getDiscriminator().isForce() );
// boolean (true here) indicates that by default column names should be guessed
ValueRelationalState relationalState = convertToSimpleValueRelationalStateIfPossible(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
xmlEntityClazz.getDiscriminator()
)
);
entityBinding.getEntity().getOrCreateSingularAttribute( bindingState.getAttributeName() );
entityBinding.makeEntityDiscriminator( bindingState.getAttributeName() )
.initialize( bindingState )
.initialize( relationalState );
}
private void bindVersion(XMLClass xmlEntityClazz,
EntityBinding entityBinding) {
if ( xmlEntityClazz.getVersion() == null && xmlEntityClazz.getTimestamp() == null ) {
return;
}
boolean isVersion = xmlEntityClazz.getVersion() != null;
String explicitName = isVersion ? xmlEntityClazz.getVersion().getName() : xmlEntityClazz.getTimestamp()
.getName();
if ( explicitName == null ) {
throw new MappingException(
"Missing property name for version/timestamp mapping [" + entityBinding.getEntity().getName() + "]"
);
}
SimpleAttributeBinding versionBinding = entityBinding.makeVersionBinding( explicitName );
if ( isVersion ) {
bindSimpleAttribute(
private void bindVersionOrTimestamp(XMLClass xmlEntityClazz,
EntityBinding entityBinding) {
if ( xmlEntityClazz.getVersion() != null ) {
bindVersion(
xmlEntityClazz.getVersion(),
versionBinding,
entityBinding,
explicitName
entityBinding
);
}
else {
bindSimpleAttribute(
else if ( xmlEntityClazz.getTimestamp() != null ) {
bindTimestamp(
xmlEntityClazz.getTimestamp(),
versionBinding,
entityBinding,
explicitName
entityBinding
);
}
}
protected void bindVersion(XMLHibernateMapping.XMLClass.XMLVersion version,
EntityBinding entityBinding) {
SimpleAttributeBindingState bindingState =
new HbmSimpleAttributeBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
getHibernateMappingBinder(),
entityBinding.getMetaAttributes(),
version
);
// boolean (true here) indicates that by default column names should be guessed
ValueRelationalState relationalState =
convertToSimpleValueRelationalStateIfPossible(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
version
)
);
entityBinding.getEntity().getOrCreateSingularAttribute( bindingState.getAttributeName() );
entityBinding.makeVersionBinding( bindingState.getAttributeName() )
.initialize( bindingState )
.initialize( relationalState );
}
protected void bindTimestamp(XMLHibernateMapping.XMLClass.XMLTimestamp timestamp,
EntityBinding entityBinding) {
SimpleAttributeBindingState bindingState =
new HbmSimpleAttributeBindingState(
entityBinding.getEntity().getPojoEntitySpecifics().getClassName(),
getHibernateMappingBinder(),
entityBinding.getMetaAttributes(),
timestamp
);
// relational model has not been bound yet
// boolean (true here) indicates that by default column names should be guessed
ValueRelationalState relationalState =
convertToSimpleValueRelationalStateIfPossible(
new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(),
true,
timestamp
)
);
entityBinding.makeVersionBinding( bindingState.getAttributeName() )
.initialize( bindingState )
.initialize( relationalState );
}
private void bindCaching(XMLClass xmlClazz,
EntityBinding entityBinding) {
XMLCacheElement cache = xmlClazz.getCache();

View File

@ -21,59 +21,71 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.hbm.state.domain;
package org.hibernate.metamodel.source.hbm.state.binding;
import java.util.Map;
import org.hibernate.metamodel.Metadata;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.MappingException;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.binding.state.AttributeBindingState;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.state.domain.AttributeDomainState;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
/**
* @author Gail Badner
*/
public abstract class AbstractHbmAttributeDomainState implements AttributeDomainState {
private final MetadataImpl metadata;
public abstract class AbstractHbmAttributeBindingState implements AttributeBindingState {
private final String ownerClassName;
private final String attributeName;
private final MappingDefaults defaults;
private final Attribute attribute;
private final String nodeName;
private final String accessorName;
private final boolean isOptimisticLockable;
private final Map<String, MetaAttribute> metaAttributes;
public AbstractHbmAttributeDomainState(
MetadataImpl metadata,
public AbstractHbmAttributeBindingState(
String ownerClassName,
String attributeName,
MappingDefaults defaults,
Attribute attribute,
String nodeName,
Map<String, MetaAttribute> metaAttributes,
String accessorName,
boolean isOptimisticLockable) {
this.metadata = metadata;
if ( attributeName == null ) {
throw new MappingException(
"Attribute name cannot be null."
);
}
this.ownerClassName = ownerClassName;
this.attributeName = attributeName;
this.defaults = defaults;
this.attribute = attribute;
this.nodeName = MappingHelper.getStringValue( nodeName, attribute.getName() );
this.nodeName = nodeName;
this.metaAttributes = metaAttributes;
this.accessorName = accessorName;
this.isOptimisticLockable = isOptimisticLockable;
}
public MetadataImpl getMetadata() {
return metadata;
// TODO: really don't like this here...
protected String getOwnerClassName() {
return ownerClassName;
}
protected final String getTypeNameByReflection() {
Class ownerClass = MappingHelper.classForName( ownerClassName, defaults.getServiceRegistry() );
return ReflectHelper.reflectedPropertyClass( ownerClass, attributeName ).getName();
}
public String getAttributeName() {
return attributeName;
}
protected final MappingDefaults getDefaults() {
return defaults;
}
public final Attribute getAttribute() {
return attribute;
}
public final String getPropertyAccessorName() {
return accessorName;
}
@ -88,10 +100,27 @@ public abstract class AbstractHbmAttributeDomainState implements AttributeDomain
}
public final String getNodeName() {
return nodeName;
return nodeName == null ? getAttributeName() : nodeName;
}
public final Map<String, MetaAttribute> getMetaAttributes() {
return metaAttributes;
}
public PropertyGeneration getPropertyGeneration() {
return PropertyGeneration.NEVER;
}
public boolean isKeyCascadeDeleteEnabled() {
return false;
}
public String getUnsavedValue() {
//TODO: implement
return null;
}
public Map<String, String> getTypeParameters() {
return null;
}
}

View File

@ -0,0 +1,76 @@
/*
* 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.hbm.state.binding;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.binding.state.DiscriminatorBindingState;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLDiscriminator;
/**
* @author Gail Badner
*/
public class HbmDiscriminatorBindingState extends AbstractHbmAttributeBindingState
implements DiscriminatorBindingState {
private final XMLDiscriminator discriminator;
public HbmDiscriminatorBindingState(
String ownerClassName,
MappingDefaults defaults,
XMLDiscriminator discriminator) {
// Discriminator.getName() is not defined, so the attribute will always be
// defaults.getDefaultDescriminatorColumnName()
super(
ownerClassName, defaults.getDefaultDiscriminatorColumnName(), defaults, null, null, null, true
);
this.discriminator = discriminator;
}
public String getCascade() {
return null;
}
protected boolean isEmbedded() {
return false;
}
public String getTypeName() {
return discriminator.getType() == null ? "string" : discriminator.getType();
}
public boolean isLazy() {
return false;
}
public boolean isInsertable() {
return discriminator.isInsert();
}
public boolean isUpdatable() {
return false;
}
public boolean isForced() {
return discriminator.isForce();
}
}

View File

@ -21,28 +21,26 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.hbm.state.domain;
package org.hibernate.metamodel.source.hbm.state.binding;
import java.util.Map;
import org.hibernate.FetchMode;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.binding.state.ManyToOneAttributeBindingState;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLManyToOneElement;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.state.domain.ManyToOneAttributeDomainState;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
/**
* @author Gail Badner
*/
public class HbmManyToOneAttributeDomainState
extends AbstractHbmAttributeDomainState
implements ManyToOneAttributeDomainState {
public class HbmManyToOneAttributeBindingState
extends AbstractHbmAttributeBindingState
implements ManyToOneAttributeBindingState {
private final HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
private final FetchMode fetchMode;
private final boolean isUnwrapProxy;
private final boolean isLazy;
@ -54,16 +52,15 @@ public class HbmManyToOneAttributeDomainState
private final boolean isInsertable;
private final boolean isUpdateable;
public HbmManyToOneAttributeDomainState(
MetadataImpl metadata,
public HbmManyToOneAttributeBindingState(
String ownerClassName,
MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
XMLManyToOneElement manyToOne) {
super(
metadata,
ownerClassName,
manyToOne.getName(),
defaults,
attribute,
manyToOne.getNode(),
HbmHelper.extractMetas( manyToOne.getMeta(), entityMetaAttributes ),
HbmHelper.getPropertyAccessorName(
@ -79,13 +76,8 @@ public class HbmManyToOneAttributeDomainState
"proxy".equals( manyToOne.getLazy().value() );
cascade = MappingHelper.getStringValue( manyToOne.getCascade(), defaults.getDefaultCascade() );
isEmbedded = manyToOne.isEmbedXml();
hibernateTypeDescriptor.setTypeName( getReferencedEntityName() );
referencedEntityName = getReferencedEntityName( ownerClassName, manyToOne, defaults );
referencedPropertyName = manyToOne.getPropertyRef();
referencedEntityName = (
manyToOne.getEntityName() == null ?
HbmHelper.getClassName( manyToOne.getClazz(), getDefaults().getPackageName() ) :
manyToOne.getEntityName().intern()
);
ignoreNotFound = "ignore".equals( manyToOne.getNotFound().value() );
isInsertable = manyToOne.isInsert();
isUpdateable = manyToOne.isUpdate();
@ -96,8 +88,19 @@ public class HbmManyToOneAttributeDomainState
return isEmbedded;
}
public HibernateTypeDescriptor getHibernateTypeDescriptor() {
return hibernateTypeDescriptor;
private static String getReferencedEntityName(String ownerClassName, XMLManyToOneElement manyToOne, MappingDefaults defaults) {
String referencedEntityName;
if ( manyToOne.getEntityName() != null ) {
referencedEntityName = manyToOne.getEntityName();
}
else if ( manyToOne.getClazz() != null ) {
referencedEntityName = HbmHelper.getClassName( manyToOne.getClazz(), defaults.getPackageName() );
}
else {
Class ownerClazz = MappingHelper.classForName( ownerClassName, defaults.getServiceRegistry() );
referencedEntityName = ReflectHelper.reflectedPropertyClass( ownerClazz, manyToOne.getName() ).getName();
}
return referencedEntityName;
}
// same as for plural attributes...
@ -121,6 +124,10 @@ public class HbmManyToOneAttributeDomainState
return fetchMode;
}
public String getTypeName() {
return referencedEntityName;
}
public FetchMode getFetchMode() {
return fetchMode;
}
@ -153,11 +160,11 @@ public class HbmManyToOneAttributeDomainState
return isInsertable;
}
public boolean isUpdateable() {
public boolean isUpdatable() {
return isUpdateable;
}
public boolean isKeyCasadeDeleteEnabled() {
public boolean isKeyCascadeDeleteEnabled() {
//TODO: implement
return false;
}

View File

@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.hbm.state.domain;
package org.hibernate.metamodel.source.hbm.state.binding;
import java.util.Comparator;
import java.util.HashMap;
@ -29,11 +29,9 @@ import java.util.HashSet;
import java.util.Map;
import org.hibernate.FetchMode;
import org.hibernate.MappingException;
import org.hibernate.metamodel.binding.CustomSQL;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.binding.state.PluralAttributeBindingState;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLBagElement;
@ -42,33 +40,27 @@ import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlDeleteElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlInsertElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSqlUpdateElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLSynchronizeElement;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.state.domain.CollectionElementDomainState;
import org.hibernate.metamodel.state.domain.PluralAttributeDomainState;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.classloading.spi.ClassLoadingException;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
/**
* @author Gail Badner
*/
public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainState
implements PluralAttributeDomainState {
public class HbmPluralAttributeBindingState extends AbstractHbmAttributeBindingState
implements PluralAttributeBindingState {
private final XMLBagElement collection;
private final HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
private final Class collectionPersisterClass;
private final String typeName;
private final String cascade;
public HbmPluralAttributeDomainState(
MetadataImpl metadata,
public HbmPluralAttributeBindingState(
String ownerClassName,
MappingDefaults mappingDefaults,
XMLBagElement collection,
Map<String, MetaAttribute> entityMetaAttributes,
Attribute attribute) {
Map<String, MetaAttribute> entityMetaAttributes) {
super(
metadata,
ownerClassName,
collection.getName(),
mappingDefaults,
attribute,
collection.getNode(),
HbmHelper.extractMetas( collection.getMeta(), entityMetaAttributes ),
HbmHelper.getPropertyAccessorName(
@ -77,9 +69,11 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
collection.isOptimisticLock()
);
this.collection = collection;
// TODO: is collection.getCollectionType() correct here?
this.hibernateTypeDescriptor.setTypeName( collection.getCollectionType() );
this.collectionPersisterClass = MappingHelper.classForName(
collection.getPersister(), getDefaults().getServiceRegistry()
);
this.cascade = MappingHelper.getStringValue( collection.getCascade(), mappingDefaults.getDefaultCascade() );
//Attribute typeNode = collectionElement.attribute( "collection-type" );
//if ( typeNode != null ) {
// TODO: implement when typedef binding is implemented
@ -95,14 +89,13 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
}
*/
//}
//TODO: fix this!!!
this.hibernateTypeDescriptor.setTypeName( collection.getCollectionType() );
typeName = collection.getCollectionType();
}
public FetchMode getFetchMode() {
FetchMode fetchMode;
if ( collection.getFetch() != null ) {
fetchMode = "join".equals( collection.getFetch() ) ? FetchMode.JOIN : FetchMode.SELECT;
fetchMode = "join".equals( collection.getFetch().value() ) ? FetchMode.JOIN : FetchMode.SELECT;
}
else {
String jfNodeValue = ( collection.getOuterJoin().value() == null ? "auto" : collection.getOuterJoin()
@ -126,11 +119,16 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
}
public boolean isExtraLazy() {
return ( "extra".equals( collection.getLazy() ) );
return ( "extra".equals( collection.getLazy().value() ) );
}
public CollectionElementDomainState getCollectionElementDomainState() {
return new HbmCollectionElementDomainState( collection.getElement() );
public String getElementTypeName() {
return collection.getElement().getTypeAttribute();
}
public String getElementNodeName() {
return collection.getElement().getNode();
}
public boolean isInverse() {
@ -142,7 +140,7 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
}
public boolean isSubselectLoadable() {
return "subselect".equals( collection.getFetch() );
return "subselect".equals( collection.getFetch().value() );
}
public String getCacheConcurrencyStrategy() {
@ -213,22 +211,7 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
}
public Class getCollectionPersisterClass() {
String className = collection.getPersister();
ClassLoaderService classLoaderService = getMetadata().getServiceRegistry()
.getService( ClassLoaderService.class );
try {
return classLoaderService.classForName( className );
}
catch ( ClassLoadingException e ) {
throw new MappingException(
"Could not find collection persister class: "
+ collection.getPersister()
);
}
}
public HibernateTypeDescriptor getHibernateTypeDescriptor() {
return hibernateTypeDescriptor;
return collectionPersisterClass;
}
public java.util.Map getFilters() {
@ -303,7 +286,7 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
return cascade;
}
public boolean isKeyCasadeDeleteEnabled() {
public boolean isKeyCascadeDeleteEnabled() {
//TODO: implement
return false;
}
@ -312,4 +295,8 @@ public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainSta
//TODO: implement
return null;
}
public String getTypeName() {
return typeName;
}
}

View File

@ -21,46 +21,46 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.hbm.state.domain;
package org.hibernate.metamodel.source.hbm.state.binding;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.MappingException;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.binding.state.SimpleAttributeBindingState;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLDiscriminator;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLId;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLTimestamp;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLVersion;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLParamElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLPropertyElement;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.state.domain.SimpleAttributeDomainState;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
/**
* @author Gail Badner
*/
public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainState
implements SimpleAttributeDomainState {
private final HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
public class HbmSimpleAttributeBindingState extends AbstractHbmAttributeBindingState
implements SimpleAttributeBindingState {
private final String typeName;
private final Map<String, String> typeParameters = new HashMap<String, String>();
private final boolean isLazy;
private final PropertyGeneration propertyGeneration;
private final boolean isInsertable;
private final boolean isUpdateable;
private final boolean isUpdatable;
public HbmSimpleAttributeDomainState(
MetadataImpl metadata,
public HbmSimpleAttributeBindingState(
String ownerClassName,
MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
XMLId id) {
super(
metadata,
ownerClassName,
id.getName() != null ? id.getName() : defaults.getDefaultIdColumnName(),
defaults,
attribute,
id.getNode(),
HbmHelper.extractMetas( id.getMeta(), entityMetaAttributes ),
HbmHelper.getPropertyAccessorName( id.getAccess(), false, defaults.getDefaultAccess() ),
@ -68,51 +68,49 @@ public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainSta
);
this.isLazy = false;
if ( id.getType() != null ) {
this.hibernateTypeDescriptor.setTypeName( id.getType().getName() );
if ( id.getTypeAttribute() != null ) {
typeName = maybeConvertToTypeDefName( id.getTypeAttribute(), defaults );
}
else if ( id.getType() != null ) {
typeName = maybeConvertToTypeDefName( id.getType().getName(), defaults );
}
else {
typeName = getTypeNameByReflection();
}
// TODO: how should these be set???
this.propertyGeneration = PropertyGeneration.parse( null );
this.isInsertable = true;
this.isUpdateable = false;
this.isUpdatable = false;
}
public HbmSimpleAttributeDomainState(
MetadataImpl metadata,
MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
XMLDiscriminator discriminator) {
super(
metadata, defaults, attribute, null, null, null, true
);
this.hibernateTypeDescriptor
.setTypeName( discriminator.getType() == null ? "string" : discriminator.getType() );
this.isLazy = false;
this.propertyGeneration = PropertyGeneration.NEVER;
this.isInsertable = discriminator.isInsert();
this.isUpdateable = false;
private static String maybeConvertToTypeDefName(String typeName, MappingDefaults defaults) {
String actualTypeName = typeName;
if ( typeName != null ) {
// TODO: tweak for typedef...
}
else {
}
return actualTypeName;
}
public HbmSimpleAttributeDomainState(
MetadataImpl metadata,
public HbmSimpleAttributeBindingState(
String ownerClassName,
MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
XMLVersion version) {
super(
metadata,
ownerClassName,
version.getName(),
defaults,
attribute,
version.getNode(),
HbmHelper.extractMetas( version.getMeta(), entityMetaAttributes ),
HbmHelper.getPropertyAccessorName( version.getAccess(), false, defaults.getDefaultAccess() ),
true
);
this.hibernateTypeDescriptor.setTypeName( version.getType() == null ? "integer" : version.getType() );
this.typeName = version.getType() == null ? "integer" : version.getType();
this.isLazy = false;
// for version properties marked as being generated, make sure they are "always"
@ -123,27 +121,27 @@ public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainSta
throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
}
this.isInsertable = MappingHelper.getBooleanValue( version.isInsert(), true );
this.isUpdateable = true;
this.isUpdatable = true;
}
public HbmSimpleAttributeDomainState(
MetadataImpl metadata,
public HbmSimpleAttributeBindingState(
String ownerClassName,
MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
XMLTimestamp timestamp) {
super(
metadata,
ownerClassName,
timestamp.getName(),
defaults,
attribute,
timestamp.getNode(),
HbmHelper.extractMetas( timestamp.getMeta(), entityMetaAttributes ),
HbmHelper.getPropertyAccessorName( timestamp.getAccess(), false, defaults.getDefaultAccess() ),
true
);
// Timestamp.getType() is not defined
this.hibernateTypeDescriptor.setTypeName( "db".equals( timestamp.getSource() ) ? "dbtimestamp" : "timestamp" );
this.typeName = "db".equals( timestamp.getSource() ) ? "dbtimestamp" : "timestamp";
this.isLazy = false;
// for version properties marked as being generated, make sure they are "always"
@ -154,19 +152,18 @@ public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainSta
throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
}
this.isInsertable = true; //TODO: is this right????
this.isUpdateable = true;
this.isUpdatable = true;
}
public HbmSimpleAttributeDomainState(
MetadataImpl metadata,
public HbmSimpleAttributeBindingState(
String ownerClassName,
MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
XMLPropertyElement property) {
super(
metadata,
ownerClassName,
property.getName(),
defaults,
attribute,
property.getNode(),
HbmHelper.extractMetas( property.getMeta(), entityMetaAttributes ),
HbmHelper.getPropertyAccessorName( property.getAccess(), false, defaults.getDefaultAccess() ),
@ -182,7 +179,7 @@ public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainSta
throw new MappingException(
"cannot specify both insert=\"true\" and generated=\"" + propertyGeneration.getName() +
"\" for property: " +
getAttribute().getName()
property.getName()
);
}
isInsertable = false;
@ -197,22 +194,55 @@ public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainSta
throw new MappingException(
"cannot specify both update=\"true\" and generated=\"" + propertyGeneration.getName() +
"\" for property: " +
getAttribute().getName()
property.getName()
);
}
isUpdateable = false;
isUpdatable = false;
}
else {
isUpdateable = MappingHelper.getBooleanValue( property.isUpdate(), true );
isUpdatable = MappingHelper.getBooleanValue( property.isUpdate(), true );
}
if ( property.getTypeAttribute() != null ) {
typeName = maybeConvertToTypeDefName( property.getTypeAttribute(), defaults );
}
else if ( property.getType() != null ) {
typeName = maybeConvertToTypeDefName( property.getType().getName(), defaults );
for ( XMLParamElement typeParameter : property.getType().getParam() ) {
//TODO: add parameters from typedef
typeParameters.put( typeParameter.getName(), typeParameter.getValue().trim() );
}
}
else {
typeName = getTypeNameByReflection();
}
// TODO: check for typedef first
/*
TypeDef typeDef = mappings.getTypeDef( typeName );
if ( typeDef != null ) {
typeName = typeDef.getTypeClass();
// parameters on the property mapping should
// override parameters in the typedef
Properties allParameters = new Properties();
allParameters.putAll( typeDef.getParameters() );
allParameters.putAll( parameters );
parameters = allParameters;
}
*/
}
protected boolean isEmbedded() {
return false;
}
public HibernateTypeDescriptor getHibernateTypeDescriptor() {
return hibernateTypeDescriptor;
public String getTypeName() {
return typeName;
}
public Map<String, String> getTypeParameters() {
return typeParameters;
}
public boolean isLazy() {
@ -227,15 +257,15 @@ public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainSta
return isInsertable;
}
public boolean isUpdateable() {
return isUpdateable;
public boolean isUpdatable() {
return isUpdatable;
}
public String getCascade() {
return null;
}
public boolean isKeyCasadeDeleteEnabled() {
public boolean isKeyCascadeDeleteEnabled() {
//TODO: implement
return false;
}

View File

@ -35,8 +35,8 @@ import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLCla
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLVersion;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLManyToOneElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLPropertyElement;
import org.hibernate.metamodel.source.util.MappingHelper;
import org.hibernate.metamodel.state.relational.ColumnRelationalState;
import org.hibernate.metamodel.source.hbm.util.MappingHelper;
import org.hibernate.metamodel.relational.state.ColumnRelationalState;
// TODO: remove duplication after Id, Discriminator, Version, Timestamp, and Property extend a common interface.

View File

@ -23,7 +23,7 @@
*/
package org.hibernate.metamodel.source.hbm.state.relational;
import org.hibernate.metamodel.state.relational.DerivedValueRelationalState;
import org.hibernate.metamodel.relational.state.DerivedValueRelationalState;
/**
* @author Gail Badner

View File

@ -23,9 +23,9 @@
*/
package org.hibernate.metamodel.source.hbm.state.relational;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.relational.state.ManyToOneRelationalState;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLManyToOneElement;
import org.hibernate.metamodel.state.relational.ManyToOneRelationalState;
/**
* @author Gail Badner

View File

@ -31,7 +31,9 @@ import java.util.Set;
import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.source.hbm.MappingDefaults;
import org.hibernate.metamodel.relational.state.SimpleValueRelationalState;
import org.hibernate.metamodel.relational.state.TupleRelationalState;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLColumnElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLDiscriminator;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLId;
@ -39,8 +41,6 @@ import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLCla
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLHibernateMapping.XMLClass.XMLVersion;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLManyToOneElement;
import org.hibernate.metamodel.source.hbm.xml.mapping.XMLPropertyElement;
import org.hibernate.metamodel.state.relational.SimpleValueRelationalState;
import org.hibernate.metamodel.state.relational.TupleRelationalState;
/**
* @author Gail Badner

View File

@ -21,13 +21,18 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.source.util;
package org.hibernate.metamodel.source.hbm.util;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.hibernate.MappingException;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.classloading.spi.ClassLoadingException;
/**
* Helper class.
*
@ -66,4 +71,17 @@ public class MappingHelper {
return tokens;
}
}
public static Class classForName(String className, ServiceRegistry serviceRegistry) {
ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
try {
return classLoaderService.classForName( className );
}
catch ( ClassLoadingException e ) {
throw new MappingException(
"Could not find class: "
+ className
);
}
}
}

View File

@ -0,0 +1,70 @@
/*
* 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 org.hibernate.MappingException;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.SingularAttribute;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
/**
* @author Gail Badner
*/
public class JavaClassNameResolver {
private final MetadataImplementor metadata;
JavaClassNameResolver(MetadataImplementor metadata) {
this.metadata = metadata;
}
public void resolve(EntityBinding entityBinding) {
// TODO: this only deals w/ POJO...
Entity entity = entityBinding.getEntity();
if ( entity == null ) {
throw new MappingException(
"Cannot resolve Java type names because the domain model has not been bound to EntityBinding." );
}
String entityClassName =
entity.getPojoEntitySpecifics().getClassName() != null ?
entity.getPojoEntitySpecifics().getClassName() :
entity.getPojoEntitySpecifics().getProxyInterfaceName();
if ( entityClassName == null ) {
throw new MappingException( "No Java class or interface defined for: " + entityBinding.getEntity().getName() );
}
for ( Attribute attribute : entity.getAttributes() ) {
if ( attribute.isSingular() ) {
SingularAttribute singularAttribute = SingularAttribute.class.cast( attribute );
if ( singularAttribute.getSingularAttributeType().getName() == null ) {
}
}
}
}
}

View File

@ -25,63 +25,121 @@ package org.hibernate.metamodel.source.internal;
import javax.persistence.SharedCacheMode;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.EJB3NamingStrategy;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.Metadata;
import org.hibernate.metamodel.MetadataBuilder;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.SourceProcessingOrder;
import org.hibernate.service.BasicServiceRegistry;
import org.hibernate.service.config.spi.ConfigurationService;
/**
* @author Steve Ebersole
*/
public class MetadataBuilderImpl implements MetadataBuilder {
private final MetadataSources sources;
private NamingStrategy namingStrategy = EJB3NamingStrategy.INSTANCE;
private SourceProcessingOrder sourceProcessingOrder = SourceProcessingOrder.HBM_FIRST;
private SharedCacheMode sharedCacheMode = SharedCacheMode.ENABLE_SELECTIVE;
private final OptionsImpl options;
public MetadataBuilderImpl(MetadataSources sources) {
this.sources = sources;
}
public MetadataSources getSources() {
return sources;
}
public NamingStrategy getNamingStrategy() {
return namingStrategy;
}
public SharedCacheMode getSharedCacheMode() {
return sharedCacheMode;
}
public SourceProcessingOrder getSourceProcessingOrder() {
return sourceProcessingOrder;
this.options = new OptionsImpl( sources.getServiceRegistry() );
}
@Override
public MetadataBuilder with(NamingStrategy namingStrategy) {
this.namingStrategy = namingStrategy;
this.options.namingStrategy = namingStrategy;
return this;
}
@Override
public MetadataBuilder with(SourceProcessingOrder sourceProcessingOrder) {
this.sourceProcessingOrder = sourceProcessingOrder;
this.options.sourceProcessingOrder = sourceProcessingOrder;
return this;
}
@Override
public MetadataBuilder with(SharedCacheMode sharedCacheMode) {
this.sharedCacheMode = sharedCacheMode;
this.options.sharedCacheMode = sharedCacheMode;
return this;
}
@Override
public MetadataBuilder with(AccessType accessType) {
this.options.defaultCacheAccessType = accessType;
return this;
}
@Override
public MetadataBuilder withNewIdentifierGeneratorsEnabled(boolean enabled) {
this.options.useNewIdentifierGenerators = enabled;
return this;
}
@Override
public Metadata buildMetadata() {
return new MetadataImpl( this );
return new MetadataImpl( sources, options );
}
private static class OptionsImpl implements Metadata.Options {
private SourceProcessingOrder sourceProcessingOrder = SourceProcessingOrder.HBM_FIRST;
private NamingStrategy namingStrategy = EJB3NamingStrategy.INSTANCE;
private SharedCacheMode sharedCacheMode = SharedCacheMode.ENABLE_SELECTIVE;
private AccessType defaultCacheAccessType;
private boolean useNewIdentifierGenerators;
public OptionsImpl(BasicServiceRegistry serviceRegistry) {
ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );
// cache access type
defaultCacheAccessType = configService.getSetting(
AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY,
new ConfigurationService.Converter<AccessType>() {
@Override
public AccessType convert(Object value) {
return AccessType.fromExternalName( value.toString() );
}
}
);
useNewIdentifierGenerators = configService.getSetting(
AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS,
new ConfigurationService.Converter<Boolean>() {
@Override
public Boolean convert(Object value) {
return Boolean.parseBoolean( value.toString() );
}
},
false
);
}
@Override
public SourceProcessingOrder getSourceProcessingOrder() {
return sourceProcessingOrder;
}
@Override
public NamingStrategy getNamingStrategy() {
return namingStrategy;
}
@Override
public AccessType getDefaultAccessType() {
return defaultCacheAccessType;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return sharedCacheMode;
}
@Override
public boolean useNewIdentifierGenerators() {
return useNewIdentifierGenerators;
}
}
}

View File

@ -30,7 +30,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.SharedCacheMode;
import org.jboss.jandex.Index;
import org.jboss.jandex.Indexer;
@ -38,7 +37,7 @@ import org.jboss.logging.Logger;
import org.hibernate.DuplicateMappingException;
import org.hibernate.HibernateException;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.SessionFactory;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.MetadataSource;
import org.hibernate.metamodel.Metadata;
@ -47,6 +46,7 @@ import org.hibernate.metamodel.SourceProcessingOrder;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.metamodel.binding.PluralAttributeBinding;
import org.hibernate.metamodel.binding.TypeDef;
import org.hibernate.metamodel.relational.Database;
import org.hibernate.metamodel.source.annotation.xml.XMLEntityMappings;
import org.hibernate.metamodel.source.annotations.AnnotationBinder;
@ -58,7 +58,7 @@ import org.hibernate.service.BasicServiceRegistry;
import org.hibernate.service.classloading.spi.ClassLoaderService;
/**
* Container for configuration data while building and binding the metamodel
* Container for configuration data collected during binding the metamodel.
*
* @author Steve Ebersole
* @author Hardy Ferentschik
@ -69,24 +69,25 @@ public class MetadataImpl implements Metadata, MetadataImplementor, Serializable
);
private final BasicServiceRegistry serviceRegistry;
private final NamingStrategy namingStrategy;
private final SharedCacheMode sharedCacheMode;
private final Options options;
private final Database database = new Database();
/**
* 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, PluralAttributeBinding> collectionBindingMap = new HashMap<String, PluralAttributeBinding>();
private Map<String, FetchProfile> fetchProfiles = new HashMap<String, FetchProfile>();
private Map<String, TypeDef> typeDefs = new HashMap<String, TypeDef>();
private Map<String, String> imports;
public MetadataImpl(MetadataBuilderImpl builder) {
final MetadataSources metadataSources = builder.getSources();
public MetadataImpl(MetadataSources metadataSources, Options options) {
this.serviceRegistry = metadataSources.getServiceRegistry();
this.namingStrategy = builder.getNamingStrategy();
this.sharedCacheMode = builder.getSharedCacheMode();
this.options = options;
final ArrayList<String> processedEntityNames = new ArrayList<String>();
if ( builder.getSourceProcessingOrder() == SourceProcessingOrder.HBM_FIRST ) {
if ( options.getSourceProcessingOrder() == SourceProcessingOrder.HBM_FIRST ) {
applyHibernateMappings( metadataSources, processedEntityNames );
applyAnnotationMappings( metadataSources, processedEntityNames );
}
@ -132,8 +133,8 @@ public class MetadataImpl implements Metadata, MetadataImplementor, Serializable
index = ormParser.parseAndUpdateIndex( mappings, index );
// create the annotation binder and pass it the final annotation index
final AnnotationBinder annotationBinder = new AnnotationBinder( this );
annotationBinder.bind( index );
final AnnotationBinder annotationBinder = new AnnotationBinder( this, index );
annotationBinder.bind();
}
/**
@ -153,22 +154,27 @@ public class MetadataImpl implements Metadata, MetadataImplementor, Serializable
}
}
@Override
public Options getOptions() {
return options;
}
@Override
public SessionFactory buildSessionFactory() {
// todo : implement!!!!
return null;
}
@Override
public BasicServiceRegistry getServiceRegistry() {
return serviceRegistry;
}
@Override
public Database getDatabase() {
return database;
}
public NamingStrategy getNamingStrategy() {
return namingStrategy;
}
public SharedCacheMode getSharedCacheMode() {
return sharedCacheMode;
}
public EntityBinding getEntityBinding(String entityName) {
return entityBindingMap.get( entityName );
}
@ -218,6 +224,15 @@ public class MetadataImpl implements Metadata, MetadataImplementor, Serializable
return fetchProfiles.values();
}
public void addTypeDef(String name, TypeDef typeDef) {
// TODO - should we check whether the typedef already exists? Log it? Exception? (HF)
typeDefs.put( name, typeDef );
}
public TypeDef getTypeDef(String name) {
return typeDefs.get( name );
}
public FetchProfile findOrCreateFetchProfile(String profileName, MetadataSource source) {
FetchProfile profile = fetchProfiles.get( profileName );
if ( profile == null ) {

View File

@ -23,17 +23,29 @@
*/
package org.hibernate.metamodel.source.spi;
import org.hibernate.mapping.MetadataSource;
import org.hibernate.metamodel.Metadata;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.metamodel.binding.PluralAttributeBinding;
import org.hibernate.metamodel.relational.Database;
import org.hibernate.service.BasicServiceRegistry;
/**
* @author Steve Ebersole
*/
public interface MetadataImplementor {
public interface MetadataImplementor extends Metadata {
public BasicServiceRegistry getServiceRegistry();
public Database getDatabase();
public Iterable<EntityBinding> getEntityBindings();
public EntityBinding getEntityBinding(String entityName);
public void addImport(String entityName, String entityName1);
public void addEntity(EntityBinding entityBinding);
public void addCollection(PluralAttributeBinding collectionBinding);
public FetchProfile findOrCreateFetchProfile(String profileName, MetadataSource hbm);
}

View File

@ -23,11 +23,8 @@
*/
package org.hibernate.service;
import org.hibernate.service.spi.BasicServiceInitiator;
/**
* @author Steve Ebersole
*/
public interface BasicServiceRegistry extends ServiceRegistry {
public void registerServiceInitiator(BasicServiceInitiator initiator);
}

View File

@ -34,6 +34,7 @@ import org.hibernate.integrator.internal.IntegratorServiceInitiator;
import org.hibernate.persister.internal.PersisterClassResolverInitiator;
import org.hibernate.persister.internal.PersisterFactoryInitiator;
import org.hibernate.service.classloading.internal.ClassLoaderServiceInitiator;
import org.hibernate.service.config.internal.ConfigurationServiceInitiator;
import org.hibernate.service.internal.SessionFactoryServiceRegistryFactoryInitiator;
import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
import org.hibernate.service.jdbc.connections.internal.MultiTenantConnectionProviderInitiator;
@ -53,6 +54,8 @@ public class StandardServiceInitiators {
private static List<BasicServiceInitiator> buildStandardServiceInitiatorList() {
final List<BasicServiceInitiator> serviceInitiators = new ArrayList<BasicServiceInitiator>();
serviceInitiators.add( ConfigurationServiceInitiator.INSTANCE );
serviceInitiators.add( ClassLoaderServiceInitiator.INSTANCE );
serviceInitiators.add( JndiServiceInitiator.INSTANCE );
serviceInitiators.add( JmxServiceInitiator.INSTANCE );

View File

@ -21,26 +21,41 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.service.spi.proxy;
package org.hibernate.service.config.internal;
import org.hibernate.service.Service;
import org.hibernate.service.ServiceRegistry;
import java.util.Collections;
import java.util.Map;
import org.hibernate.service.config.spi.ConfigurationService;
/**
* Additional contract for service proxies. This allows the proxies access to their actual service instances.
*
* @author Steve Ebersole
*/
public interface ServiceProxyTargetSource extends ServiceRegistry {
/**
* Retrieve a service by role. Unlike {@link ServiceRegistry#getService}, this version will never return a proxy.
*
* @param serviceRole The service role
* @param <R> The service role type
*
* @return The requested service.
*
* @throws org.hibernate.service.UnknownServiceException Indicates the service was not known.
*/
public <R extends Service> R getServiceInternal(Class<R> serviceRole);
public class ConfigurationServiceImpl implements ConfigurationService {
private final Map settings;
@SuppressWarnings( "unchecked" )
public ConfigurationServiceImpl(Map settings) {
this.settings = Collections.unmodifiableMap( settings );
}
@Override
public Map getSettings() {
return settings;
}
@Override
public <T> T getSetting(String name, Converter<T> converter) {
return getSetting( name, converter, null );
}
@Override
public <T> T getSetting(String name, Converter<T> converter, T defaultValue) {
final Object value = settings.get( name );
if ( value == null ) {
return defaultValue;
}
return converter.convert( value );
}
}

View File

@ -21,20 +21,26 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.service.internal.proxy.javassist;
package org.hibernate.service.config.internal;
import org.hibernate.service.spi.proxy.ServiceProxyFactory;
import org.hibernate.service.spi.proxy.ServiceProxyFactoryFactory;
import org.hibernate.service.spi.proxy.ServiceProxyTargetSource;
import java.util.Map;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.spi.BasicServiceInitiator;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* Javassist-based implementation of a {@link ServiceProxyFactoryFactory}
*
* @author Steve Ebersole
*/
public class ServiceProxyFactoryFactoryImpl implements ServiceProxyFactoryFactory {
public class ConfigurationServiceInitiator implements BasicServiceInitiator<ConfigurationService> {
public static final ConfigurationServiceInitiator INSTANCE = new ConfigurationServiceInitiator();
public ConfigurationService initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
return new ConfigurationServiceImpl( configurationValues );
}
@Override
public ServiceProxyFactory makeServiceProxyFactory(ServiceProxyTargetSource registry) {
return new ServiceProxyFactoryImpl( registry );
public Class<ConfigurationService> getServiceInitiated() {
return ConfigurationService.class;
}
}

View File

@ -21,23 +21,24 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.service.spi.proxy;
package org.hibernate.service.config.spi;
import java.util.Map;
import org.hibernate.service.Service;
/**
* Contract for creating proxy instances for {@link Service} instances.
* Provides access to the initial user-provided configuration values
*
* @author Steve Ebersole
*/
public interface ServiceProxyFactory {
/**
* Create a proxy for the given service role.
*
* @param serviceRole The service role for which to create a proxy.
* @param <T> The type of the service
*
* @return The service proxy
*/
public <T extends Service> T makeProxy(Class<T> serviceRole);
public interface ConfigurationService extends Service {
public Map getSettings();
public <T> T getSetting(String name, Converter<T> converter);
public <T> T getSetting(String name, Converter<T> converter, T defaultValue);
public static interface Converter<T> {
public T convert(Object value);
}
}

View File

@ -31,32 +31,29 @@ import java.util.concurrent.ConcurrentHashMap;
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.service.Service;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.internal.proxy.javassist.ServiceProxyFactoryFactoryImpl;
import org.hibernate.service.UnknownServiceException;
import org.hibernate.service.jmx.spi.JmxService;
import org.hibernate.service.spi.InjectService;
import org.hibernate.service.spi.Manageable;
import org.hibernate.service.spi.ServiceBinding;
import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceInitiator;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.Startable;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.service.UnknownServiceException;
import org.hibernate.service.spi.proxy.ServiceProxyFactory;
/**
* @author Steve Ebersole
*/
public abstract class AbstractServiceRegistryImpl implements ServiceRegistryImplementor {
public abstract class AbstractServiceRegistryImpl implements ServiceRegistryImplementor, ServiceBinding.OwningRegistry {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, AbstractServiceRegistryImpl.class.getName() );
private final ServiceRegistryImplementor parent;
// for now just hard-code the javassist factory
private ServiceProxyFactory serviceProxyFactory = new ServiceProxyFactoryFactoryImpl().makeServiceProxyFactory( this );
private ConcurrentHashMap<Class,ServiceBinding> serviceBindingMap;
// IMPL NOTE : the list used for ordered destruction. Cannot used map above because we need to
// iterate it in reverse order which is only available through ListIterator
@ -73,6 +70,20 @@ public abstract class AbstractServiceRegistryImpl implements ServiceRegistryImpl
this.serviceList = CollectionHelper.arrayList( 20 );
}
@SuppressWarnings({ "unchecked" })
protected <R extends Service> void createServiceBinding(ServiceInitiator<R> initiator) {
serviceBindingMap.put( initiator.getServiceInitiated(), new ServiceBinding( this, initiator ) );
}
protected <R extends Service> void createServiceBinding(ProvidedService<R> providedService) {
ServiceBinding<R> binding = locateServiceBinding( providedService.getServiceRole(), false );
if ( binding == null ) {
binding = new ServiceBinding<R>( this, providedService.getServiceRole(), providedService.getService() );
serviceBindingMap.put( providedService.getServiceRole(), binding );
}
registerService( binding, providedService.getService() );
}
@Override
@SuppressWarnings( {"unchecked"})
public ServiceRegistry getParentServiceRegistry() {
@ -97,40 +108,33 @@ public abstract class AbstractServiceRegistryImpl implements ServiceRegistryImpl
@Override
public <R extends Service> R getService(Class<R> serviceRole) {
return locateOrCreateServiceBinding( serviceRole, true ).getProxy();
}
@SuppressWarnings({ "unchecked" })
protected <R extends Service> ServiceBinding<R> locateOrCreateServiceBinding(Class<R> serviceRole, boolean checkParent) {
ServiceBinding<R> serviceBinding = locateServiceBinding( serviceRole, checkParent );
final ServiceBinding<R> serviceBinding = locateServiceBinding( serviceRole );
if ( serviceBinding == null ) {
createServiceBinding( serviceRole );
throw new UnknownServiceException( serviceRole );
}
return serviceBinding;
R service = serviceBinding.getService();
if ( service == null ) {
service = initializeService( serviceBinding );
}
return service;
}
protected <R extends Service> ServiceBinding<R> createServiceBinding(Class<R> serviceRole) {
R proxy = serviceProxyFactory.makeProxy( serviceRole );
ServiceBinding<R> serviceBinding = new ServiceBinding<R>( proxy );
serviceBindingMap.put( serviceRole, serviceBinding );
return serviceBinding;
}
protected <R extends Service> void registerService(Class<R> serviceRole, R service) {
ServiceBinding<R> serviceBinding = locateOrCreateServiceBinding( serviceRole, false );
R priorServiceInstance = serviceBinding.getTarget();
serviceBinding.setTarget( service );
protected <R extends Service> void registerService(ServiceBinding<R> serviceBinding, R service) {
R priorServiceInstance = serviceBinding.getService();
serviceBinding.setService( service );
if ( priorServiceInstance != null ) {
serviceList.remove( priorServiceInstance );
}
serviceList.add( service );
}
private <R extends Service> R initializeService(Class<R> serviceRole) {
LOG.trace("Initializing service [role=" + serviceRole.getName() + "]");
private <R extends Service> R initializeService(ServiceBinding<R> serviceBinding) {
LOG.trace( "Initializing service [role=" + serviceBinding.getServiceRole().getName() + "]" );
// PHASE 1 : create service
R service = createService( serviceRole );
R service = createService( serviceBinding );
if ( service == null ) {
return null;
}
@ -139,12 +143,34 @@ public abstract class AbstractServiceRegistryImpl implements ServiceRegistryImpl
configureService( service );
// PHASE 3 : Start service
startService( service, serviceRole );
startService( serviceBinding );
return service;
}
protected abstract <T extends Service> T createService(Class<T> serviceRole);
@SuppressWarnings( {"unchecked"})
protected <R extends Service> R createService(ServiceBinding<R> serviceBinding) {
final ServiceInitiator<R> serviceInitiator = serviceBinding.getServiceInitiator();
if ( serviceInitiator == null ) {
// this condition should never ever occur
throw new UnknownServiceException( serviceBinding.getServiceRole() );
}
try {
R service = serviceBinding.getServiceRegistry().initiateService( serviceInitiator );
// IMPL NOTE : the register call here is important to avoid potential stack overflow issues
// from recursive calls through #configureService
registerService( serviceBinding, service );
return service;
}
catch ( ServiceException e ) {
throw e;
}
catch ( Exception e ) {
throw new ServiceException( "Unable to create requested service [" + serviceBinding.getServiceRole().getName() + "]", e );
}
}
protected abstract <T extends Service> void configureService(T service);
protected <T extends Service> void applyInjections(T service) {
@ -197,36 +223,19 @@ public abstract class AbstractServiceRegistryImpl implements ServiceRegistryImpl
}
@SuppressWarnings({ "unchecked" })
protected <T extends Service> void startService(T service, Class serviceRole) {
if ( Startable.class.isInstance( service ) ) {
( (Startable) service ).start();
protected <R extends Service> void startService(ServiceBinding<R> serviceBinding) {
if ( Startable.class.isInstance( serviceBinding.getService() ) ) {
( (Startable) serviceBinding.getService() ).start();
}
if ( Manageable.class.isInstance( service ) ) {
getService( JmxService.class ).registerService( (Manageable) service, serviceRole );
if ( Manageable.class.isInstance( serviceBinding.getService() ) ) {
getService( JmxService.class ).registerService(
(Manageable) serviceBinding.getService(),
serviceBinding.getServiceRole()
);
}
}
@Override
@SuppressWarnings( {"unchecked"})
public <R extends Service> R getServiceInternal(Class<R> serviceRole) {
// this call comes from the binding proxy, we most definitely do not want to look up into the parent
// in this case!
ServiceBinding<R> serviceBinding = locateServiceBinding( serviceRole, false );
if ( serviceBinding == null ) {
throw new HibernateException( "Only proxies should invoke #getServiceInternal" );
}
R service = serviceBinding.getTarget();
if ( service == null ) {
service = initializeService( serviceRole );
serviceBinding.setTarget( service );
}
if ( service == null ) {
throw new UnknownServiceException( serviceRole );
}
return service;
}
public void destroy() {
ListIterator<Service> serviceIterator = serviceList.listIterator( serviceList.size() );
while ( serviceIterator.hasPrevious() ) {

View File

@ -23,19 +23,14 @@
*/
package org.hibernate.service.internal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jboss.logging.Logger;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.service.BasicServiceRegistry;
import org.hibernate.service.Service;
import org.hibernate.service.UnknownServiceException;
import org.hibernate.service.spi.BasicServiceInitiator;
import org.hibernate.service.spi.Configurable;
import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceInitiator;
import org.hibernate.service.spi.ServiceRegistryAwareService;
/**
@ -44,86 +39,33 @@ import org.hibernate.service.spi.ServiceRegistryAwareService;
* @author Steve Ebersole
*/
public class BasicServiceRegistryImpl extends AbstractServiceRegistryImpl implements BasicServiceRegistry {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, BasicServiceRegistryImpl.class.getName());
private final Map<Class,BasicServiceInitiator> serviceInitiatorMap;
private final Map configurationValues;
@SuppressWarnings( {"unchecked"})
public BasicServiceRegistryImpl(
List<BasicServiceInitiator> serviceInitiators,
List<ProvidedService> providedServices,
Map configurationValues) {
final List<BasicServiceInitiator> serviceInitiators,
final List<ProvidedService> providedServices,
final Map configurationValues) {
super();
this.configurationValues = configurationValues;
this.serviceInitiatorMap = toMap( serviceInitiators );
for ( BasicServiceInitiator initiator : serviceInitiatorMap.values() ) {
// create the bindings up front to help identify to which registry services belong
createServiceBinding( initiator.getServiceInitiated() );
// process initiators
for ( ServiceInitiator initiator : serviceInitiators ) {
createServiceBinding( initiator );
}
// then, explicitly provided service instances
for ( ProvidedService providedService : providedServices ) {
ServiceBinding binding = locateOrCreateServiceBinding( providedService.getServiceRole(), false );
binding.setTarget( providedService.getService() );
}
}
/**
* We convert the incoming list of initiators to a map for 2 reasons:<ul>
* <li>to make it easier to look up the initiator we need for a given service role</li>
* <li>to make sure there is only one initiator for a given service role (last wins)</li>
* </ul>
*
* @param serviceInitiators The list of individual initiators
*
* @return The map of initiators keyed by the service rle they initiate.
*/
private static Map<Class, BasicServiceInitiator> toMap(List<BasicServiceInitiator> serviceInitiators) {
final Map<Class, BasicServiceInitiator> result = new HashMap<Class, BasicServiceInitiator>();
for ( BasicServiceInitiator initiator : serviceInitiators ) {
result.put( initiator.getServiceInitiated(), initiator );
}
return result;
}
@Override
@SuppressWarnings( {"unchecked"})
public void registerServiceInitiator(BasicServiceInitiator initiator) {
ServiceBinding serviceBinding = locateServiceBinding( initiator.getServiceInitiated(), false );
if ( serviceBinding != null ) {
serviceBinding.setTarget( null );
}
else {
createServiceBinding( initiator.getServiceInitiated() );
}
final Object previous = serviceInitiatorMap.put( initiator.getServiceInitiated(), initiator );
if ( previous != null ) {
LOG.debugf( "Over-wrote existing service initiator [role=%s]", initiator.getServiceInitiated().getName() );
createServiceBinding( providedService );
}
}
@Override
@SuppressWarnings({ "unchecked" })
protected <T extends Service> T createService(Class<T> serviceRole) {
BasicServiceInitiator<T> initiator = serviceInitiatorMap.get( serviceRole );
if ( initiator == null ) {
throw new UnknownServiceException( serviceRole );
}
try {
T service = initiator.initiateService( configurationValues, this );
// IMPL NOTE : the register call here is important to avoid potential stack overflow issues
// from recursive calls through #configureService
registerService( serviceRole, service );
return service;
}
catch ( ServiceException e ) {
throw e;
}
catch ( Exception e ) {
throw new ServiceException( "Unable to create requested service [" + serviceRole.getName() + "]", e );
}
public <R extends Service> R initiateService(ServiceInitiator<R> serviceInitiator) {
// todo : add check/error for unexpected initiator types?
return ( (BasicServiceInitiator<R>) serviceInitiator ).initiateService( configurationValues, this );
}
@Override

View File

@ -28,20 +28,20 @@ package org.hibernate.service.internal;
*
* @author Steve Ebersole
*/
public class ProvidedService<T> {
private final Class<T> serviceRole;
private final T service;
public class ProvidedService<R> {
private final Class<R> serviceRole;
private final R service;
public ProvidedService(Class<T> serviceRole, T service) {
public ProvidedService(Class<R> serviceRole, R service) {
this.serviceRole = serviceRole;
this.service = service;
}
public Class<T> getServiceRole() {
public Class<R> getServiceRole() {
return serviceRole;
}
public T getService() {
public R getService() {
return service;
}
}

View File

@ -23,19 +23,11 @@
*/
package org.hibernate.service.internal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jboss.logging.Logger;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.Service;
import org.hibernate.service.StandardSessionFactoryServiceInitiators;
import org.hibernate.service.UnknownServiceException;
import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceInitiator;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceInitiator;
@ -44,13 +36,7 @@ import org.hibernate.service.spi.SessionFactoryServiceRegistry;
/**
* @author Steve Ebersole
*/
public class SessionFactoryServiceRegistryImpl
extends AbstractServiceRegistryImpl
implements SessionFactoryServiceRegistry {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, SessionFactoryServiceRegistryImpl.class.getName() );
private final Map<Class,SessionFactoryServiceInitiator> serviceInitiatorMap;
public class SessionFactoryServiceRegistryImpl extends AbstractServiceRegistryImpl implements SessionFactoryServiceRegistry {
// for now we need to hold on to the Configuration... :(
private Configuration configuration;
@ -62,62 +48,21 @@ public class SessionFactoryServiceRegistryImpl
SessionFactoryImplementor sessionFactory,
Configuration configuration) {
super( parent );
// for now, just use the standard initiator list
this.serviceInitiatorMap = toMap( StandardSessionFactoryServiceInitiators.LIST );
this.sessionFactory = sessionFactory;
this.configuration = configuration;
for ( SessionFactoryServiceInitiator initiator : serviceInitiatorMap.values() ) {
// for now, just use the standard initiator list
for ( SessionFactoryServiceInitiator initiator : StandardSessionFactoryServiceInitiators.LIST ) {
// create the bindings up front to help identify to which registry services belong
createServiceBinding( initiator.getServiceInitiated() );
}
}
private static Map<Class, SessionFactoryServiceInitiator> toMap(List<SessionFactoryServiceInitiator> serviceInitiators) {
final Map<Class, SessionFactoryServiceInitiator> result = new HashMap<Class, SessionFactoryServiceInitiator>();
for ( SessionFactoryServiceInitiator initiator : serviceInitiators ) {
result.put( initiator.getServiceInitiated(), initiator );
}
return result;
}
@Override
@SuppressWarnings( {"unchecked"})
public void registerServiceInitiator(SessionFactoryServiceInitiator initiator) {
ServiceBinding serviceBinding = locateServiceBinding( initiator.getServiceInitiated(), false );
if ( serviceBinding != null ) {
serviceBinding.setTarget( null );
}
else {
createServiceBinding( initiator.getServiceInitiated() );
}
final Object previous = serviceInitiatorMap.put( initiator.getServiceInitiated(), initiator );
if ( previous != null ) {
LOG.debugf( "Over-wrote existing service initiator [role=%s]", initiator.getServiceInitiated().getName() );
createServiceBinding( initiator );
}
}
@Override
@SuppressWarnings({ "unchecked" })
protected <T extends Service> T createService(Class<T> serviceRole) {
SessionFactoryServiceInitiator<T> initiator = serviceInitiatorMap.get( serviceRole );
if ( initiator == null ) {
throw new UnknownServiceException( serviceRole );
}
try {
T service = initiator.initiateService( sessionFactory, configuration, this );
// IMPL NOTE : the register call here is important to avoid potential stack overflow issues
// from recursive calls through #configureService
registerService( serviceRole, service );
return service;
}
catch ( ServiceException e ) {
throw e;
}
catch ( Exception e ) {
throw new ServiceException( "Unable to create requested service [" + serviceRole.getName() + "]", e );
}
public <R extends Service> R initiateService(ServiceInitiator<R> serviceInitiator) {
// todo : add check/error for unexpected initiator types?
return ( (SessionFactoryServiceInitiator<R>) serviceInitiator ).initiateService( sessionFactory, configuration, this );
}
@Override

View File

@ -1,124 +0,0 @@
/*
* 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.service.internal.proxy.javassist;
import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;
import org.hibernate.service.internal.ServiceProxy;
import org.hibernate.service.internal.ServiceProxyGenerationException;
import org.hibernate.service.Service;
import org.hibernate.service.spi.proxy.ServiceProxyFactory;
import org.hibernate.service.spi.proxy.ServiceProxyTargetSource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Javassist-based implementation of a {@link ServiceProxyFactory}
*
* @author Steve Ebersole
*/
public class ServiceProxyFactoryImpl implements ServiceProxyFactory {
private final ServiceProxyTargetSource serviceRegistry;
public ServiceProxyFactoryImpl(ServiceProxyTargetSource serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
private static final MethodFilter FINALIZE_FILTER = new MethodFilter() {
public boolean isHandled(Method m) {
// skip finalize methods
return !( m.getParameterTypes().length == 0 && m.getName().equals( "finalize" ) );
}
};
@Override
@SuppressWarnings( {"unchecked"})
public <T extends Service> T makeProxy(Class<T> serviceRole) {
try {
ProxyFactory factory = new ProxyFactory();
factory.setFilter( FINALIZE_FILTER );
Class[] interfaces = new Class[2];
interfaces[0] = serviceRole;
interfaces[1] = ServiceProxy.class;
factory.setInterfaces( interfaces );
Class proxyClass = factory.createClass();
ProxyObject proxyObject = (ProxyObject) proxyClass.newInstance();
proxyObject.setHandler( new ServiceProxyMethodInterceptor<T>( (T)proxyObject, serviceRole, serviceRegistry ) );
return (T) proxyObject;
}
catch (Exception e) {
throw new ServiceProxyGenerationException( "Unable to make service proxy", e );
}
}
private static class ServiceProxyMethodInterceptor<T extends Service> implements MethodHandler {
private final T proxy;
private final Class<T> serviceRole;
private final ServiceProxyTargetSource serviceRegistry;
private ServiceProxyMethodInterceptor(T proxy, Class<T> serviceRole, ServiceProxyTargetSource serviceRegistry) {
this.proxy = proxy;
this.serviceRole = serviceRole;
this.serviceRegistry = serviceRegistry;
}
@Override
@SuppressWarnings( {"UnnecessaryBoxing"} )
public Object invoke(
Object object,
Method method,
Method method1,
Object[] args) throws Exception {
String name = method.getName();
if ( "toString".equals( name ) ) {
return serviceRole.getName() + "_$$_Proxy@" + System.identityHashCode( object );
}
else if ( "equals".equals( name ) ) {
return proxy == object ? Boolean.TRUE : Boolean.FALSE;
}
else if ( "hashCode".equals( name ) ) {
return Integer.valueOf( System.identityHashCode( object ) );
}
else if ( "getTargetInstance".equals( name ) && ServiceProxy.class.equals( method.getDeclaringClass() ) ) {
return serviceRegistry.getServiceInternal( serviceRole );
}
else {
try {
T target = serviceRegistry.getServiceInternal( serviceRole );
return method.invoke( target, args );
}
catch (InvocationTargetException e) {
throw (Exception) e.getTargetException();
}
}
}
}
}

View File

@ -32,14 +32,7 @@ import org.hibernate.service.Service;
*
* @author Steve Ebersole
*/
public interface BasicServiceInitiator<R extends Service> {
/**
* Obtains the service role initiated by this initiator. Should be unique within a registry
*
* @return The service role.
*/
public Class<R> getServiceInitiated();
public interface BasicServiceInitiator<R extends Service> extends ServiceInitiator<R> {
/**
* Initiates the managed service.
*

View File

@ -0,0 +1,81 @@
/*
* 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.service.spi;
import org.jboss.logging.Logger;
import org.hibernate.service.Service;
/**
* Models a binding for a particular service
* @author Steve Ebersole
*/
public final class ServiceBinding<R extends Service> {
private static final Logger log = Logger.getLogger( ServiceBinding.class );
public static interface OwningRegistry {
public <R extends Service> R initiateService(ServiceInitiator<R> serviceInitiator);
}
private final OwningRegistry serviceRegistry;
private final Class<R> serviceRole;
private final ServiceInitiator<R> serviceInitiator;
private R service;
public ServiceBinding(OwningRegistry serviceRegistry, Class<R> serviceRole, R service) {
this.serviceRegistry = serviceRegistry;
this.serviceRole = serviceRole;
this.serviceInitiator = null;
this.service = service;
}
public ServiceBinding(OwningRegistry serviceRegistry, ServiceInitiator<R> serviceInitiator) {
this.serviceRegistry = serviceRegistry;
this.serviceRole = serviceInitiator.getServiceInitiated();
this.serviceInitiator = serviceInitiator;
}
public OwningRegistry getServiceRegistry() {
return serviceRegistry;
}
public Class<R> getServiceRole() {
return serviceRole;
}
public ServiceInitiator<R> getServiceInitiator() {
return serviceInitiator;
}
public R getService() {
return service;
}
public void setService(R service) {
if ( this.service != null ) {
log.debug( "Overriding existing service binding [" + serviceRole.getName() + "]" );
}
this.service = service;
}
}

View File

@ -21,14 +21,18 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.metamodel.state.domain;
package org.hibernate.service.spi;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.binding.SingularAttributeBinding;
import org.hibernate.service.Service;
/**
* @author Gail Badner
* @author Steve Ebersole
*/
public interface SimpleAttributeDomainState extends SingularAttributeDomainState {
public PropertyGeneration getPropertyGeneration();
public interface ServiceInitiator<R extends Service> {
/**
* Obtains the service role initiated by this initiator. Should be unique within a registry
*
* @return The service role.
*/
public Class<R> getServiceInitiated();
}

View File

@ -25,34 +25,11 @@ package org.hibernate.service.spi;
import org.hibernate.service.Service;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.proxy.ServiceProxyTargetSource;
/**
* @author Steve Ebersole
*/
public interface ServiceRegistryImplementor extends ServiceRegistry, ServiceProxyTargetSource {
public interface ServiceRegistryImplementor extends ServiceRegistry {
public <R extends Service> ServiceBinding<R> locateServiceBinding(Class<R> serviceRole);
public void destroy();
public final class ServiceBinding<R> {
private final R proxy;
private R target;
public ServiceBinding(R proxy) {
this.proxy = proxy;
}
public R getProxy() {
return proxy;
}
public R getTarget() {
return target;
}
public void setTarget(R target) {
this.target = target;
}
}
}

View File

@ -30,14 +30,7 @@ import org.hibernate.service.Service;
/**
* @author Steve Ebersole
*/
public interface SessionFactoryServiceInitiator<R extends Service> {
/**
* Obtains the service role initiated by this initiator. Should be unique within a registry
*
* @return The service role.
*/
public Class<R> getServiceInitiated();
public interface SessionFactoryServiceInitiator<R extends Service> extends ServiceInitiator<R>{
/**
* Initiates the managed service.
* <p/>

View File

@ -30,5 +30,4 @@ package org.hibernate.service.spi;
* @author Steve Ebersole
*/
public interface SessionFactoryServiceRegistry extends ServiceRegistryImplementor {
public void registerServiceInitiator(SessionFactoryServiceInitiator initiator);
}

View File

@ -1,40 +0,0 @@
/*
* 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.service.spi.proxy;
/**
* Contract for making a {@link ServiceProxyFactory}.
*
* @author Steve Ebersole
*/
public interface ServiceProxyFactoryFactory {
/**
* Make an instance of the service proxy factory.
*
* @param registry The registry of actual service instances
*
* @return The created service proxy factory
*/
public ServiceProxyFactory makeServiceProxyFactory(ServiceProxyTargetSource registry);
}

View File

@ -26,9 +26,9 @@ package org.hibernate.stat.internal;
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceInitiator;
@ -90,7 +90,6 @@ public class StatisticsInitiator implements SessionFactoryServiceInitiator<Stati
statistics.setStatisticsEnabled( enabled );
LOG.debugf( "Statistics initialized [enabled=%s]", enabled );
return statistics;
}
private static StatisticsFactory DEFAULT_STATS_BUILDER = new StatisticsFactory() {

View File

@ -24,18 +24,21 @@
package org.hibernate.metamodel.binding;
import java.util.Iterator;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.BasicServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.internal.BasicServiceRegistryImpl;
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.assertNull;
@ -50,10 +53,12 @@ import static org.junit.Assert.assertTrue;
public abstract class AbstractBasicBindingTests extends BaseUnitTestCase {
private BasicServiceRegistryImpl serviceRegistry;
private MetadataSources sources;
@Before
public void setUp() {
serviceRegistry = (BasicServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
}
@After
@ -67,75 +72,57 @@ public abstract class AbstractBasicBindingTests extends BaseUnitTestCase {
@Test
public void testSimpleEntityMapping() {
checkSimpleEntityMapping( buildSimpleEntityBinding() );
}
MetadataImpl metadata = addSourcesForSimpleEntityBinding( sources );
EntityBinding entityBinding = metadata.getEntityBinding( SimpleEntity.class.getName() );
assertIdAndSimpleProperty( entityBinding );
protected void checkSimpleEntityMapping(EntityBinding entityBinding) {
assertNotNull( entityBinding );
assertNotNull( entityBinding.getEntityIdentifier() );
assertNotNull( entityBinding.getEntityIdentifier().getValueBinding() );
assertNull( entityBinding.getVersioningValueBinding() );
AttributeBinding idAttributeBinding = entityBinding.getAttributeBinding( "id" );
assertNotNull( idAttributeBinding );
assertSame( idAttributeBinding, entityBinding.getEntityIdentifier().getValueBinding() );
assertNotNull( idAttributeBinding.getAttribute() );
assertNotNull( idAttributeBinding.getValue() );
assertTrue( idAttributeBinding.getValue() instanceof Column );
AttributeBinding nameBinding = entityBinding.getAttributeBinding( "name" );
assertNotNull( nameBinding );
assertNotNull( nameBinding.getAttribute() );
assertNotNull( nameBinding.getValue() );
}
@Test
public void testSimpleVersionedEntityMapping() {
EntityBinding entityBinding = buildSimpleVersionedEntityBinding();
assertNotNull( entityBinding );
assertNotNull( entityBinding.getEntityIdentifier() );
assertNotNull( entityBinding.getEntityIdentifier().getValueBinding() );
MetadataImpl metadata = addSourcesForSimpleVersionedEntityBinding( sources );
EntityBinding entityBinding = metadata.getEntityBinding( SimpleVersionedEntity.class.getName() );
assertIdAndSimpleProperty( entityBinding );
assertNotNull( entityBinding.getVersioningValueBinding() );
assertNotNull( entityBinding.getVersioningValueBinding().getAttribute() );
AttributeBinding idAttributeBinding = entityBinding.getAttributeBinding( "id" );
assertNotNull( idAttributeBinding );
assertSame( idAttributeBinding, entityBinding.getEntityIdentifier().getValueBinding() );
assertNotNull( idAttributeBinding.getAttribute() );
assertNotNull( idAttributeBinding.getValue() );
assertTrue( idAttributeBinding.getValue() instanceof Column );
AttributeBinding nameBinding = entityBinding.getAttributeBinding( "name" );
assertNotNull( nameBinding );
assertNotNull( nameBinding.getAttribute() );
assertNotNull( nameBinding.getValue() );
}
@Test
public void testEntityWithManyToOneMapping() {
MetadataImplementor metadata = buildMetadataWithManyToOne();
EntityBinding entityWithManyToOneBinding = metadata.getEntityBinding( EntityWithManyToOne.class.getName() );
EntityBinding simpleEntityBinding = metadata.getEntityBinding( SimpleEntity.class.getName() );
checkSimpleEntityMapping( simpleEntityBinding );
MetadataImpl metadata = addSourcesForManyToOne( sources );
assertTrue(
1 == simpleEntityBinding.getAttributeBinding( "id" ).getEntityReferencingAttributeBindings().size()
);
EntityBinding simpleEntityBinding = metadata.getEntityBinding( SimpleEntity.class.getName() );
assertIdAndSimpleProperty( simpleEntityBinding );
Set<EntityReferencingAttributeBinding> referenceBindings = simpleEntityBinding.getAttributeBinding( "id" )
.getEntityReferencingAttributeBindings();
assertEquals( "There should be only one reference binding", 1, referenceBindings.size() );
EntityReferencingAttributeBinding referenceBinding = referenceBindings.iterator().next();
EntityBinding referencedEntityBinding = referenceBinding.getReferencedEntityBinding();
// TODO - Is this assertion correct (HF)?
assertEquals( "Should be the same entity binding", referencedEntityBinding, simpleEntityBinding );
EntityBinding entityWithManyToOneBinding = metadata.getEntityBinding( ManyToOneEntity.class.getName() );
Iterator<EntityReferencingAttributeBinding> it = entityWithManyToOneBinding.getEntityReferencingAttributeBindings()
.iterator();
assertTrue( it.hasNext() );
assertSame( entityWithManyToOneBinding.getAttributeBinding( "simpleEntity" ), it.next() );
assertFalse( it.hasNext() );
}
/*
@Test
public void testEntityWithElementCollection() {
EntityBinding entityBinding = buildEntityWithElementCollectionBinding();
public abstract MetadataImpl addSourcesForSimpleVersionedEntityBinding(MetadataSources sources);
public abstract MetadataImpl addSourcesForSimpleEntityBinding(MetadataSources sources);
public abstract MetadataImpl addSourcesForManyToOne(MetadataSources sources);
protected void assertIdAndSimpleProperty(EntityBinding entityBinding) {
assertNotNull( entityBinding );
assertNotNull( entityBinding.getEntityIdentifier() );
assertNotNull( entityBinding.getEntityIdentifier().getValueBinding() );
assertNull( entityBinding.getVersioningValueBinding() );
AttributeBinding idAttributeBinding = entityBinding.getAttributeBinding( "id" );
assertNotNull( idAttributeBinding );
@ -149,13 +136,4 @@ public abstract class AbstractBasicBindingTests extends BaseUnitTestCase {
assertNotNull( nameBinding.getAttribute() );
assertNotNull( nameBinding.getValue() );
}
*/
public abstract EntityBinding buildSimpleVersionedEntityBinding();
public abstract EntityBinding buildSimpleEntityBinding();
public abstract MetadataImplementor buildMetadataWithManyToOne();
//public abstract EntityBinding buildEntityWithElementCollectionBinding();
}

View File

@ -27,8 +27,6 @@ import org.junit.Test;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.FailureExpected;
/**
@ -43,26 +41,20 @@ public class BasicAnnotationBindingTests extends AbstractBasicBindingTests {
super.testEntityWithManyToOneMapping();
}
public EntityBinding buildSimpleEntityBinding() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
public MetadataImpl addSourcesForSimpleEntityBinding(MetadataSources sources) {
sources.addAnnotatedClass( SimpleEntity.class );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
return (MetadataImpl) sources.buildMetadata();
return metadata.getEntityBinding( SimpleEntity.class.getSimpleName() );
}
public EntityBinding buildSimpleVersionedEntityBinding() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
public MetadataImpl addSourcesForSimpleVersionedEntityBinding(MetadataSources sources) {
sources.addAnnotatedClass( SimpleVersionedEntity.class );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
return metadata.getEntityBinding( SimpleVersionedEntity.class.getSimpleName() );
return (MetadataImpl) sources.buildMetadata();
}
public MetadataImplementor buildMetadataWithManyToOne() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addAnnotatedClass( EntityWithManyToOne.class );
sources.addAnnotatedClass( SimpleVersionedEntity.class );
return (MetadataImplementor) sources.buildMetadata();
public MetadataImpl addSourcesForManyToOne(MetadataSources sources) {
sources.addAnnotatedClass( ManyToOneEntity.class );
sources.addAnnotatedClass( SimpleEntity.class );
return (MetadataImpl) sources.buildMetadata();
}
}

View File

@ -25,9 +25,6 @@ package org.hibernate.metamodel.binding;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.metamodel.source.spi.MetadataImplementor;
import static org.junit.Assert.assertEquals;
/**
* Basic tests of {@code hbm.xml} binding code
@ -35,33 +32,19 @@ import static org.junit.Assert.assertEquals;
* @author Steve Ebersole
*/
public class BasicHbmBindingTests extends AbstractBasicBindingTests {
public EntityBinding buildSimpleEntityBinding() {
return getEntityBinding(
"org/hibernate/metamodel/binding/SimpleEntity.hbm.xml",
SimpleEntity.class.getName()
);
public MetadataImpl addSourcesForSimpleEntityBinding(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/SimpleEntity.hbm.xml" );
return (MetadataImpl) sources.buildMetadata();
}
public EntityBinding buildSimpleVersionedEntityBinding() {
return getEntityBinding(
"org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml",
SimpleVersionedEntity.class.getName()
);
public MetadataImpl addSourcesForSimpleVersionedEntityBinding(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml" );
return (MetadataImpl) sources.buildMetadata();
}
public MetadataImplementor buildMetadataWithManyToOne() {
MetadataSources metadataSources = new MetadataSources( basicServiceRegistry() );
metadataSources.addResource( "org/hibernate/metamodel/binding/EntityWithManyToOne.hbm.xml" );
metadataSources.addResource( "org/hibernate/metamodel/binding/SimpleEntity.hbm.xml" );
assertEquals( 2, metadataSources.getJaxbRootList().size() );
return ( MetadataImplementor ) metadataSources.buildMetadata();
}
private EntityBinding getEntityBinding(String resourceName, String entityName ) {
MetadataSources metadataSources = new MetadataSources( basicServiceRegistry() );
metadataSources.addResource( resourceName );
assertEquals( 1, metadataSources.getJaxbRootList().size() );
MetadataImpl metadata = ( MetadataImpl ) metadataSources.buildMetadata();
return metadata.getEntityBinding( entityName );
public MetadataImpl addSourcesForManyToOne(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/ManyToOneEntity.hbm.xml" );
sources.addResource( "org/hibernate/metamodel/binding/SimpleEntity.hbm.xml" );
return (MetadataImpl) sources.buildMetadata();
}
}

View File

@ -1,15 +0,0 @@
<?xml version="1.0"?>
<hhh:hibernate-mapping package="org.hibernate.metamodel.binding" xmlns:hhh="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="EntityWithManyToOne">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<many-to-one name="simpleEntity"/>
</class>
</hhh:hibernate-mapping>

View File

@ -0,0 +1,15 @@
<?xml version="1.0"?>
<hhh:hibernate-mapping package="org.hibernate.metamodel.binding"
xmlns:hhh="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="ManyToOneEntity">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<many-to-one name="simpleEntity"/>
</class>
</hhh:hibernate-mapping>

View File

@ -23,9 +23,6 @@
*/
package org.hibernate.metamodel.binding;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@ -35,17 +32,18 @@ import org.hibernate.annotations.Entity;
* @author Gail Badner
*/
@Entity
public class EntityWithManyToOne {
public class ManyToOneEntity {
@Id
private Long id;
private String theName;
@ManyToOne
SimpleEntity simpleEntity;
public EntityWithManyToOne() {
public ManyToOneEntity() {
}
public EntityWithManyToOne(String name) {
this.theName = theName;
public ManyToOneEntity(String name) {
this.theName = name;
}
public Long getId() {
@ -61,10 +59,9 @@ public class EntityWithManyToOne {
}
public void setName(String name) {
this.theName = theName;
this.theName = name;
}
@ManyToOne
public SimpleEntity getSimpleEntity() {
return simpleEntity;
}
@ -72,4 +69,15 @@ public class EntityWithManyToOne {
public void setSimpleEntity(SimpleEntity simpleEntity) {
this.simpleEntity = simpleEntity;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "EntityWithManyToOne" );
sb.append( "{id=" ).append( id );
sb.append( ", theName='" ).append( theName ).append( '\'' );
sb.append( ", simpleEntity=" ).append( simpleEntity );
sb.append( '}' );
return sb.toString();
}
}

Some files were not shown because too many files have changed in this diff Show More