HHH-6134 : Migrate processing hbm.xml files to use Jaxb-generated classes

This commit is contained in:
Gail Badner 2011-04-18 15:13:18 -07:00
parent c88fcff77a
commit eb414295aa
35 changed files with 1845 additions and 812 deletions

View File

@ -24,6 +24,9 @@
package org.hibernate; package org.hibernate;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.metamodel.source.Origin;
import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
import org.hibernate.metamodel.source.internal.JaxbRoot;
/** /**
* Thrown when a mapping is found to be invalid. * Thrown when a mapping is found to be invalid.
@ -56,6 +59,10 @@ public InvalidMappingException(String customMessage, XmlDocument xmlDocument) {
this( customMessage, xmlDocument.getOrigin().getType(), xmlDocument.getOrigin().getName() ); this( customMessage, xmlDocument.getOrigin().getType(), xmlDocument.getOrigin().getName() );
} }
public InvalidMappingException(String customMessage, Origin origin) {
this( customMessage, origin.getType().toString(), origin.getName() );
}
public InvalidMappingException(String type, String path) { public InvalidMappingException(String type, String path) {
this("Could not parse mapping document from " + type + (path==null?"":" " + path), type, path); this("Could not parse mapping document from " + type + (path==null?"":" " + path), type, path);
} }

View File

@ -28,18 +28,14 @@
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.dom4j.Element;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.metamodel.domain.Attribute; import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.relational.Column; import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.DerivedValue; import org.hibernate.metamodel.relational.DerivedValue;
import org.hibernate.metamodel.relational.SimpleValue; import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.relational.TableSpecification; import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.relational.Tuple; import org.hibernate.metamodel.relational.Tuple;
import org.hibernate.metamodel.relational.Value; import org.hibernate.metamodel.relational.Value;
import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.util.DomHelper;
/** /**
* TODO : javadoc * TODO : javadoc

View File

@ -25,9 +25,8 @@
import java.util.Map; import java.util.Map;
import org.hibernate.FetchMode;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.metamodel.domain.Attribute; import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.relational.SimpleValue; import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.relational.TableSpecification; import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.relational.Value; import org.hibernate.metamodel.relational.Value;

View File

@ -25,8 +25,7 @@
import org.dom4j.Element; import org.dom4j.Element;
import org.hibernate.mapping.PropertyGeneration; import org.hibernate.metamodel.relational.Value;
import org.hibernate.mapping.Value;
import org.hibernate.metamodel.source.hbm.HbmHelper; import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.source.util.DomHelper;

View File

@ -29,18 +29,15 @@
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.engine.Versioning; import org.hibernate.engine.Versioning;
import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.metamodel.domain.Entity; import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.relational.Column; import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.TableSpecification; import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.source.hbm.HbmHelper; import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* TODO : javadoc * TODO : javadoc
@ -86,21 +83,20 @@ public class EntityBinding {
private List<String> synchronizedTableNames; private List<String> synchronizedTableNames;
// TODO: change to intialize from Doimain // TODO: change to intialize from Doimain
public void fromHbmXml(MappingDefaults defaults, Element node, Entity entity) { public void fromHbmXml(MappingDefaults defaults, org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz, Entity entity) {
this.entity = entity; this.entity = entity;
metaAttributes = HbmHelper.extractMetas( node, true, defaults.getMappingMetas() ); metaAttributes = HbmHelper.extractMetas( entityClazz.getMeta(), true, defaults.getMappingMetas() );
// go ahead and set the lazy here, since pojo.proxy can override it. // go ahead and set the lazy here, since pojo.proxy can override it.
lazy = DomHelper.extractBooleanAttributeValue( node, "lazy", defaults.isDefaultLazy() ); lazy = MappingHelper.getBooleanValue( entityClazz.getLazy(), defaults.isDefaultLazy() );
discriminatorValue = MappingHelper.getStringValue( entityClazz.getDiscriminatorValue(), entity.getName() );
discriminatorValue = DomHelper.extractAttributeValue( node, "discriminator-value", entity.getName() ); dynamicUpdate = MappingHelper.getBooleanValue( entityClazz.getDynamicUpdate(), false );
dynamicUpdate = DomHelper.extractBooleanAttributeValue( node, "dynamic-update", false ); dynamicInsert = MappingHelper.getBooleanValue( entityClazz.getDynamicInsert(), false );
dynamicInsert = DomHelper.extractBooleanAttributeValue( node, "dynamic-insert", false ); batchSize = MappingHelper.getIntValue( entityClazz.getBatchSize(), 0 );
batchSize = DomHelper.extractIntAttributeValue( node, "batch-size", 0 ); selectBeforeUpdate = MappingHelper.getBooleanValue( entityClazz.getSelectBeforeUpdate(), false );
selectBeforeUpdate = DomHelper.extractBooleanAttributeValue( node, "select-before-update", false );
// OPTIMISTIC LOCK MODE // OPTIMISTIC LOCK MODE
String optimisticLockModeString = DomHelper.extractAttributeValue( node, "optimistic-lock", "version" ); String optimisticLockModeString = MappingHelper.getStringValue( entityClazz.getOptimisticLock(), "version" );
if ( "version".equals( optimisticLockModeString ) ) { if ( "version".equals( optimisticLockModeString ) ) {
optimisticLockMode = Versioning.OPTIMISTIC_LOCK_VERSION; optimisticLockMode = Versioning.OPTIMISTIC_LOCK_VERSION;
} }
@ -118,28 +114,51 @@ else if ( "none".equals( optimisticLockModeString ) ) {
} }
// PERSISTER // PERSISTER
Attribute persisterNode = node.attribute( "persister" ); if ( entityClazz.getPersister() != null ) {
if ( persisterNode != null ) {
try { try {
entityPersisterClass = ReflectHelper.classForName( persisterNode.getValue() ); entityPersisterClass = ReflectHelper.classForName( entityClazz.getPersister() );
} }
catch (ClassNotFoundException cnfe) { catch (ClassNotFoundException cnfe) {
throw new MappingException( "Could not find persister class: " throw new MappingException( "Could not find persister class: "
+ persisterNode.getValue() ); + entityClazz.getPersister() );
} }
} }
// CUSTOM SQL // CUSTOM SQL
customInsert = HbmHelper.getCustomSql( node.element( "sql-insert" ) ); org.hibernate.metamodel.source.hbm.xml.mapping.SqlInsert sqlInsert = entityClazz.getSqlInsert();
customDelete = HbmHelper.getCustomSql( node.element( "sql-delete" ) ); if ( sqlInsert != null ) {
customUpdate = HbmHelper.getCustomSql( node.element( "sql-update" ) ); customInsert = HbmHelper.getCustomSql(
sqlInsert.getContent(),
Iterator tables = node.elementIterator( "synchronize" ); MappingHelper.getBooleanValue( sqlInsert.getCallable(), false ),
while ( tables.hasNext() ) { sqlInsert.getCheck()
addSynchronizedTable( ( ( Element ) tables.next() ).attributeValue( "table" ) ); );
} }
isAbstract = DomHelper.extractBooleanAttributeValue( node, "abstract", false ); org.hibernate.metamodel.source.hbm.xml.mapping.SqlDelete sqlDelete = entityClazz.getSqlDelete();
if ( sqlDelete != null ) {
customDelete = HbmHelper.getCustomSql(
sqlDelete.getContent(),
MappingHelper.getBooleanValue( sqlDelete.getCallable(), false ),
sqlDelete.getCheck()
);
}
org.hibernate.metamodel.source.hbm.xml.mapping.SqlUpdate sqlUpdate = entityClazz.getSqlUpdate();
if ( sqlUpdate != null ) {
customUpdate = HbmHelper.getCustomSql(
sqlUpdate.getContent(),
MappingHelper.getBooleanValue( sqlUpdate.getCallable(), false ),
sqlUpdate.getCheck()
);
}
if ( entityClazz.getSynchronize() != null ) {
for ( org.hibernate.metamodel.source.hbm.xml.mapping.Synchronize synchronize : entityClazz.getSynchronize() ) {
addSynchronizedTable( synchronize.getTable() );
}
}
isAbstract = MappingHelper.getBooleanValue( entityClazz.getAbstract(), false );
} }
public Entity getEntity() { public Entity getEntity() {

View File

@ -0,0 +1,143 @@
/*
* 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;
import java.util.LinkedHashSet;
import org.hibernate.mapping.MetadataSource;
/**
* A fetch profile allows a user to dynamically modify the fetching strategy used for particular associations at
* runtime, whereas that information was historically only statically defined in the metadata.
* <p/>
* This class represent the data as it is defined in their metadata.
*
* @author Steve Ebersole
*
* @see org.hibernate.engine.profile.FetchProfile
*/
public class FetchProfile {
private final String name;
private final MetadataSource source;
private LinkedHashSet<Fetch> fetches = new LinkedHashSet<Fetch>();
/**
* Create a fetch profile representation.
*
* @param name The name of the fetch profile.
* @param source The source of the fetch profile (where was it defined).
*/
public FetchProfile(String name, MetadataSource source) {
this.name = name;
this.source = source;
}
/**
* Retrieve the name of the fetch profile.
*
* @return The profile name
*/
public String getName() {
return name;
}
/**
* Retrieve the fetch profile source.
*
* @return The profile source.
*/
public MetadataSource getSource() {
return source;
}
/**
* Retrieve the fetches associated with this profile
*
* @return The fetches associated with this profile.
*/
public LinkedHashSet<Fetch> getFetches() {
return fetches;
}
/**
* Adds a fetch to this profile.
*
* @param entity The entity which contains the association to be fetched
* @param association The association to fetch
* @param style The style of fetch t apply
*/
public void addFetch(String entity, String association, String style) {
fetches.add( new Fetch( entity, association, style ) );
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
FetchProfile that = (FetchProfile) o;
return name.equals( that.name );
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return name.hashCode();
}
/**
* Defines an individual association fetch within the given profile.
*/
public static class Fetch {
private final String entity;
private final String association;
private final String style;
public Fetch(String entity, String association, String style) {
this.entity = entity;
this.association = association;
this.style = style;
}
public String getEntity() {
return entity;
}
public String getAssociation() {
return association;
}
public String getStyle() {
return style;
}
}
}

View File

@ -0,0 +1,73 @@
/*
* 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;
import java.io.Serializable;
import java.util.Properties;
/**
* Identifier generator container,
* Useful to keep named generator in annotations
*
* @author Emmanuel Bernard
*/
public class IdGenerator implements Serializable {
private String name;
private String identifierGeneratorStrategy;
private Properties params = new Properties();
/**
* @return identifier generator strategy
*/
public String getIdentifierGeneratorStrategy() {
return identifierGeneratorStrategy;
}
/**
* @return generator name
*/
public String getName() {
return name;
}
/**
* @return generator configuration parameters
*/
public Properties getParams() {
return params;
}
public void setIdentifierGeneratorStrategy(String string) {
identifierGeneratorStrategy = string;
}
public void setName(String string) {
name = string;
}
public void addParam(String key, String value) {
params.setProperty( key, value );
}
}

View File

@ -26,7 +26,7 @@
import java.util.Map; import java.util.Map;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.mapping.MetaAttribute; import org.hibernate.metamodel.domain.MetaAttribute;
/** /**
* @author Gail Badner * @author Gail Badner

View File

@ -156,105 +156,6 @@ public void initialize(DomainState state) {
} }
public void fromHbmXml(MappingDefaults defaults, Element element, org.hibernate.metamodel.domain.Attribute attribute) {
inverse = DomHelper.extractBooleanAttributeValue( element, "inverse", false );
mutable = DomHelper.extractBooleanAttributeValue( element, "mutable", true );
if ( "subselect".equals( element.attributeValue("fetch") ) ) {
subselectLoadable = true;
getEntityBinding().setSubselectLoadableCollections( true );
}
orderBy = DomHelper.extractAttributeValue( element, "order-by", null );
where = DomHelper.extractAttributeValue( element, "where", null );
batchSize = DomHelper.extractIntAttributeValue( element, "batch-size", 0 );
embedded = DomHelper.extractBooleanAttributeValue( element, "embed-xml", true );
try {
collectionPersisterClass = DomHelper.extractClassAttributeValue( element, "persister" );
}
catch (ClassNotFoundException cnfe) {
throw new MappingException( "Could not find collection persister class: "
+ element.attributeValue( "persister" ) );
}
//Attribute typeNode = collectionElement.attribute( "collection-type" );
//if ( typeNode != null ) {
// TODO: implement when typedef binding is implemented
/*
String typeName = typeNode.getValue();
TypeDef typeDef = mappings.getTypeDef( typeName );
if ( typeDef != null ) {
collectionBinding.setTypeName( typeDef.getTypeClass() );
collectionBinding.setTypeParameters( typeDef.getParameters() );
}
else {
collectionBinding.setTypeName( typeName );
}
*/
//}
// SORT
// unsorted, natural, comparator.class.name
String sortString = DomHelper.extractAttributeValue( element, "sort", "unsorted" );
sorted = ( ! "unsorted".equals( sortString ) );
if ( sorted && ! "natural".equals( sortString ) ) {
comparatorClassName = sortString;
}
// ORPHAN DELETE (used for programmer error detection)
String cascadeString = DomHelper.extractAttributeValue( element, "cascade", "none" );
orphanDelete = ( cascadeString.indexOf( "delete-orphan" ) >= 0 );
// CUSTOM SQL
customSQLInsert = HbmHelper.getCustomSql( element.element( "sql-insert" ) );
customSQLDelete = HbmHelper.getCustomSql( element.element( "sql-delete" ) );
customSQLUpdate = HbmHelper.getCustomSql( element.element( "sql-update" ) );
customSQLDeleteAll = HbmHelper.getCustomSql( element.element( "sql-delete-all" ) );
// TODO: IMPLEMENT
//Iterator iter = collectionElement.elementIterator( "filter" );
//while ( iter.hasNext() ) {
// final Element filter = (Element) iter.next();
// parseFilter( filter, collectionElement, collectionBinding );
//}
Iterator tables = element.elementIterator( "synchronize" );
while ( tables.hasNext() ) {
synchronizedTables.add( ( (Element ) tables.next() ).attributeValue( "table" ) );
}
loaderName = DomHelper.extractAttributeValue( element.element( "loader" ), "query-ref" );
referencedPropertyName = element.element( "key" ).attributeValue( "property-ref" );
Element cacheElement = element.element( "cache" );
if ( cacheElement != null ) {
cacheConcurrencyStrategy = cacheElement.attributeValue( "usage" );
cacheRegionName = cacheElement.attributeValue( "region" );
}
Attribute fetchNode = element.attribute( "fetch" );
if ( fetchNode != null ) {
fetchMode = "join".equals( fetchNode.getValue() ) ? FetchMode.JOIN : FetchMode.SELECT;
}
else {
Attribute jfNode = element.attribute( "outer-join" );
String jfNodeValue = ( jfNode == null ? "auto" : jfNode.getValue() );
if ( "auto".equals( jfNodeValue ) ) {
fetchMode = FetchMode.DEFAULT;
}
else if ( "true".equals( jfNodeValue ) ) {
fetchMode = FetchMode.JOIN;
}
else {
fetchMode = FetchMode.SELECT;
}
}
String lazyString = DomHelper.extractAttributeValue( element, "lazy" );
extraLazy = ( "extra".equals( lazyString ) );
if ( extraLazy && ! isLazy() ) {
// explicitly make lazy
setLazy( true );
}
}
protected boolean isLazyDefault(MappingDefaults defaults) { protected boolean isLazyDefault(MappingDefaults defaults) {
return defaults.isDefaultLazy(); return defaults.isDefaultLazy();

View File

@ -69,7 +69,7 @@ public static interface DerivedRelationalState extends SingleValueRelationalStat
} }
public static interface TupleRelationalState { public static interface TupleRelationalState {
LinkedHashSet<SingleValueRelationalState> getSingleValueRelationalStates(); Set<SingleValueRelationalState> getSingleValueRelationalStates();
} }
private PropertyGeneration generation; private PropertyGeneration generation;

View File

@ -0,0 +1,48 @@
/*
* 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;
import java.io.Serializable;
import java.util.Properties;
/**
* Placeholder for typedef information
*/
public class TypeDef implements Serializable {
private String typeClass;
private Properties parameters;
public TypeDef(String typeClass, Properties parameters) {
this.typeClass = typeClass;
this.parameters = parameters;
}
public Properties getParameters() {
return parameters;
}
public String getTypeClass() {
return typeClass;
}
}

View File

@ -0,0 +1,67 @@
/*
* 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.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
/**
* A meta attribute is a named value or values.
* @author Gavin King
*/
public class MetaAttribute implements Serializable {
private String name;
private java.util.List values = new ArrayList();
public MetaAttribute(String name) {
this.name = name;
}
public String getName() {
return name;
}
public java.util.List getValues() {
return Collections.unmodifiableList(values);
}
public void addValue(String value) {
values.add(value);
}
public String getValue() {
if ( values.size()!=1 ) {
throw new IllegalStateException("no unique value");
}
return (String) values.get(0);
}
public boolean isMultiValued() {
return values.size()>1;
}
public String toString() {
return "[" + name + "=" + values + "]";
}
}

View File

@ -0,0 +1,64 @@
/*
* 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.relational;
import java.util.HashSet;
import org.hibernate.dialect.Dialect;
import org.hibernate.mapping.AuxiliaryDatabaseObject;
/**
* Convenience base class for {@link org.hibernate.mapping.AuxiliaryDatabaseObject}s.
* <p/>
* This implementation performs dialect scoping checks strictly based on
* dialect name comparisons. Custom implementations might want to do
* instanceof-type checks.
*
* @author Steve Ebersole
*/
public abstract class AbstractAuxiliaryDatabaseObject implements AuxiliaryDatabaseObject {
private final HashSet dialectScopes;
protected AbstractAuxiliaryDatabaseObject() {
this.dialectScopes = new HashSet();
}
protected AbstractAuxiliaryDatabaseObject(HashSet dialectScopes) {
this.dialectScopes = dialectScopes;
}
public void addDialectScope(String dialectName) {
dialectScopes.add( dialectName );
}
public HashSet getDialectScopes() {
return dialectScopes;
}
public boolean appliesToDialect(Dialect dialect) {
// empty means no scoping
return dialectScopes.isEmpty() || dialectScopes.contains( dialect.getClass().getName() );
}
}

View File

@ -0,0 +1,54 @@
/*
* 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.relational;
import java.io.Serializable;
import org.hibernate.dialect.Dialect;
import org.hibernate.mapping.RelationalModel;
/**
* Auxiliary database objects (i.e., triggers, stored procedures, etc) defined
* in the mappings. Allows Hibernate to manage their lifecycle as part of
* creating/dropping the schema.
*
* @author Steve Ebersole
*/
public interface AuxiliaryDatabaseObject extends RelationalModel, Serializable {
/**
* Add the given dialect name to the scope of dialects to which
* this database object applies.
*
* @param dialectName The name of a dialect.
*/
void addDialectScope(String dialectName);
/**
* Does this database object apply to the given dialect?
*
* @param dialect The dialect to check against.
* @return True if this database object does apply to the given dialect.
*/
boolean appliesToDialect(Dialect dialect);
}

View File

@ -23,6 +23,7 @@
*/ */
package org.hibernate.metamodel.source.hbm; package org.hibernate.metamodel.source.hbm;
import java.sql.ResultSet;
import java.util.Iterator; import java.util.Iterator;
import org.dom4j.Attribute; import org.dom4j.Attribute;
@ -31,6 +32,7 @@
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.engine.Versioning; import org.hibernate.engine.Versioning;
import org.hibernate.engine.jdbc.batch.spi.Batch;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.metamodel.binding.AttributeBinding; import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.BagBinding; import org.hibernate.metamodel.binding.BagBinding;
@ -39,6 +41,7 @@
import org.hibernate.metamodel.binding.SimpleAttributeBinding; import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.domain.Entity; import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.Hierarchical; import org.hibernate.metamodel.domain.Hierarchical;
import org.hibernate.metamodel.domain.PluralAttribute;
import org.hibernate.metamodel.domain.PluralAttributeNature; import org.hibernate.metamodel.domain.PluralAttributeNature;
import org.hibernate.metamodel.relational.Schema; import org.hibernate.metamodel.relational.Schema;
import org.hibernate.metamodel.relational.Table; import org.hibernate.metamodel.relational.Table;
@ -58,20 +61,17 @@ abstract class AbstractEntityBinder {
private final HibernateMappingBinder hibernateMappingBinder; private final HibernateMappingBinder hibernateMappingBinder;
private final Schema.Name schemaName; private final Schema.Name schemaName;
AbstractEntityBinder(HibernateMappingBinder hibernateMappingBinder, Element entityElement) { AbstractEntityBinder(HibernateMappingBinder hibernateMappingBinder,
org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz) {
this.hibernateMappingBinder = hibernateMappingBinder; this.hibernateMappingBinder = hibernateMappingBinder;
this.schemaName = new Schema.Name(
final Attribute schemaAttribute = entityElement.attribute( "schema" ); ( entityClazz.getSchema() == null ?
String schemaName = ( schemaAttribute == null ) hibernateMappingBinder.getDefaultSchemaName() :
? hibernateMappingBinder.getDefaultSchemaName() entityClazz.getSchema() ),
: schemaAttribute.getValue(); ( entityClazz.getCatalog() == null ?
hibernateMappingBinder.getDefaultCatalogName() :
final Attribute catalogAttribute = entityElement.attribute( "catalog" ); entityClazz.getCatalog() )
String catalogName = ( catalogAttribute == null ) );
? hibernateMappingBinder.getDefaultCatalogName()
: catalogAttribute.getValue();
this.schemaName = new Schema.Name( schemaName, catalogName );
} }
protected HibernateMappingBinder getHibernateMappingBinder() { protected HibernateMappingBinder getHibernateMappingBinder() {
@ -93,23 +93,24 @@ protected NamingStrategy getNamingStrategy() {
return getMetadata().getNamingStrategy(); return getMetadata().getNamingStrategy();
} }
protected void basicEntityBinding(Element node, EntityBinding entityBinding, Hierarchical superType) { protected void basicEntityBinding(org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
EntityBinding entityBinding,
Hierarchical superType) {
entityBinding.fromHbmXml( entityBinding.fromHbmXml(
hibernateMappingBinder, hibernateMappingBinder,
node, entityClazz,
new Entity( hibernateMappingBinder.extractEntityName( node ), superType ) new Entity( hibernateMappingBinder.extractEntityName( entityClazz ), superType )
); );
// TODO: move this stuff out // TODO: move this stuff out
// transfer an explicitly defined lazy attribute // transfer an explicitly defined lazy attribute
bindPojoRepresentation( node, entityBinding ); bindPojoRepresentation( entityClazz, entityBinding );
bindDom4jRepresentation( node, entityBinding ); bindDom4jRepresentation( entityClazz, entityBinding );
bindMapRepresentation( node, entityBinding ); bindMapRepresentation( entityClazz, entityBinding );
final String entityName = entityBinding.getEntity().getName(); final String entityName = entityBinding.getEntity().getName();
Iterator itr = node.elementIterator( "fetch-profile" );
while ( itr.hasNext() ) { if ( entityClazz.getFetchProfile() != null ) {
final Element profileElement = ( Element ) itr.next(); hibernateMappingBinder.parseFetchProfiles( entityClazz.getFetchProfile(), entityName );
hibernateMappingBinder.parseFetchProfile( profileElement, entityName );
} }
getMetadata().addImport( entityName, entityName ); getMetadata().addImport( entityName, entityName );
@ -124,9 +125,10 @@ protected String getDefaultAccess() {
return hibernateMappingBinder.getDefaultAccess(); return hibernateMappingBinder.getDefaultAccess();
} }
private void bindPojoRepresentation(Element node, EntityBinding entityBinding) { private void bindPojoRepresentation(org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
String className = hibernateMappingBinder.getClassName( node.attribute( "name" ) ); EntityBinding entityBinding) {
String proxyName = hibernateMappingBinder.getClassName( node.attribute( "proxy" ) ); String className = hibernateMappingBinder.getClassName( entityClazz.getName() );
String proxyName = hibernateMappingBinder.getClassName( entityClazz.getProxy() );
entityBinding.getEntity().getPojoEntitySpecifics().setClassName( className ); entityBinding.getEntity().getPojoEntitySpecifics().setClassName( className );
@ -138,29 +140,31 @@ else if ( entityBinding.isLazy() ) {
entityBinding.getEntity().getPojoEntitySpecifics().setProxyInterfaceName( className ); entityBinding.getEntity().getPojoEntitySpecifics().setProxyInterfaceName( className );
} }
Element tuplizer = locateTuplizerDefinition( node, EntityMode.POJO ); org.hibernate.metamodel.source.hbm.xml.mapping.Tuplizer tuplizer = locateTuplizerDefinition( entityClazz, EntityMode.POJO );
if ( tuplizer != null ) { if ( tuplizer != null ) {
entityBinding.getEntity().getPojoEntitySpecifics().setTuplizerClassName( tuplizer.attributeValue( "class" ) ); entityBinding.getEntity().getPojoEntitySpecifics().setTuplizerClassName( tuplizer.getClazz() );
} }
} }
private void bindDom4jRepresentation(Element node, EntityBinding entityBinding) { private void bindDom4jRepresentation(org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
String nodeName = node.attributeValue( "node" ); EntityBinding entityBinding) {
String nodeName = entityClazz.getNode();
if ( nodeName == null ) { if ( nodeName == null ) {
nodeName = StringHelper.unqualify( entityBinding.getEntity().getName() ); nodeName = StringHelper.unqualify( entityBinding.getEntity().getName() );
} }
entityBinding.getEntity().getDom4jEntitySpecifics().setNodeName(nodeName); entityBinding.getEntity().getDom4jEntitySpecifics().setNodeName(nodeName);
Element tuplizer = locateTuplizerDefinition( node, EntityMode.DOM4J ); org.hibernate.metamodel.source.hbm.xml.mapping.Tuplizer tuplizer = locateTuplizerDefinition( entityClazz, EntityMode.DOM4J );
if ( tuplizer != null ) { if ( tuplizer != null ) {
entityBinding.getEntity().getDom4jEntitySpecifics().setTuplizerClassName( tuplizer.attributeValue( "class" ) ); entityBinding.getEntity().getDom4jEntitySpecifics().setTuplizerClassName( tuplizer.getClazz() );
} }
} }
private void bindMapRepresentation(Element node, EntityBinding entityBinding) { private void bindMapRepresentation(org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
Element tuplizer = locateTuplizerDefinition( node, EntityMode.MAP ); EntityBinding entityBinding) {
org.hibernate.metamodel.source.hbm.xml.mapping.Tuplizer tuplizer = locateTuplizerDefinition( entityClazz, EntityMode.MAP );
if ( tuplizer != null ) { if ( tuplizer != null ) {
entityBinding.getEntity().getMapEntitySpecifics().setTuplizerClassName( tuplizer.attributeValue( "class" ) ); entityBinding.getEntity().getMapEntitySpecifics().setTuplizerClassName( tuplizer.getClazz() );
} }
} }
@ -172,12 +176,11 @@ private void bindMapRepresentation(Element node, EntityBinding entityBinding) {
* *
* @return The tuplizer element, or null. * @return The tuplizer element, or null.
*/ */
private static Element locateTuplizerDefinition(Element container, EntityMode entityMode) { private static org.hibernate.metamodel.source.hbm.xml.mapping.Tuplizer locateTuplizerDefinition(org.hibernate.metamodel.source.hbm.xml.mapping.Class container,
Iterator itr = container.elementIterator( "tuplizer" ); EntityMode entityMode) {
while( itr.hasNext() ) { for ( org.hibernate.metamodel.source.hbm.xml.mapping.Tuplizer tuplizer : container.getTuplizer() ) {
final Element tuplizerElem = ( Element ) itr.next(); if ( entityMode.toString().equals( tuplizer.getEntityMode() ) ) {
if ( entityMode.toString().equals( tuplizerElem.attributeValue( "entity-mode") ) ) { return tuplizer;
return tuplizerElem;
} }
} }
return null; return null;
@ -206,19 +209,18 @@ else if ( "none".equals( olMode ) ) {
} }
protected String getClassTableName( protected String getClassTableName(
Element entityElement, org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
EntityBinding entityBinding, EntityBinding entityBinding,
Table denormalizedSuperTable) { Table denormalizedSuperTable) {
final String entityName = entityBinding.getEntity().getName(); final String entityName = entityBinding.getEntity().getName();
final Attribute tableNameNode = entityElement.attribute( "table" );
String logicalTableName; String logicalTableName;
String physicalTableName; String physicalTableName;
if ( tableNameNode == null ) { if ( entityClazz.getTable() == null ) {
logicalTableName = StringHelper.unqualify( entityName ); logicalTableName = StringHelper.unqualify( entityName );
physicalTableName = getHibernateXmlBinder().getMetadata().getNamingStrategy().classToTableName( entityName ); physicalTableName = getHibernateXmlBinder().getMetadata().getNamingStrategy().classToTableName( entityName );
} }
else { else {
logicalTableName = tableNameNode.getValue(); logicalTableName = entityClazz.getTable();
physicalTableName = getHibernateXmlBinder().getMetadata().getNamingStrategy().tableName( logicalTableName ); physicalTableName = getHibernateXmlBinder().getMetadata().getNamingStrategy().tableName( logicalTableName );
} }
// todo : find out the purpose of these logical bindings // todo : find out the purpose of these logical bindings
@ -226,25 +228,26 @@ protected String getClassTableName(
return physicalTableName; return physicalTableName;
} }
protected void buildAttributeBindings(Element entityElement, EntityBinding entityBinding) { protected void buildAttributeBindings(org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
EntityBinding entityBinding) {
// null = UniqueKey (we are not binding a natural-id mapping) // null = UniqueKey (we are not binding a natural-id mapping)
// true = mutable, by default properties are mutable // true = mutable, by default properties are mutable
// true = nullable, by default properties are nullable. // true = nullable, by default properties are nullable.
buildAttributeBindings( entityElement, entityBinding, null, true, true ); buildAttributeBindings( entityClazz, entityBinding, null, true, true );
} }
/** /**
* This form is essentially used to create natural-id mappings. But the processing is the same, aside from these * This form is essentially used to create natural-id mappings. But the processing is the same, aside from these
* extra parameterized values, so we encapsulate it here. * extra parameterized values, so we encapsulate it here.
* *
* @param entityElement * @param entityClazz
* @param entityBinding * @param entityBinding
* @param uniqueKey * @param uniqueKey
* @param mutable * @param mutable
* @param nullable * @param nullable
*/ */
protected void buildAttributeBindings( protected void buildAttributeBindings(
Element entityElement, org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz,
EntityBinding entityBinding, EntityBinding entityBinding,
UniqueKey uniqueKey, UniqueKey uniqueKey,
boolean mutable, boolean mutable,
@ -255,69 +258,68 @@ protected void buildAttributeBindings(
final TableSpecification tabe = entityBinding.getBaseTable(); final TableSpecification tabe = entityBinding.getBaseTable();
AttributeBinding attributeBinding = null; AttributeBinding attributeBinding = null;
for ( Object attribute : entityClazz.getPropertyOrManyToOneOrOneToOne() ) {
Iterator iter = entityElement.elementIterator(); if ( org.hibernate.metamodel.source.hbm.xml.mapping.Bag.class.isInstance( attribute ) ) {
while ( iter.hasNext() ) { org.hibernate.metamodel.source.hbm.xml.mapping.Bag collection = org.hibernate.metamodel.source.hbm.xml.mapping.Bag.class.cast( attribute );
final Element subElement = (Element) iter.next(); BagBinding collectionBinding = entityBinding.makeBagAttributeBinding( collection.getName() );
final String subElementName = subElement.getName(); bindBag( collection, collectionBinding, entityBinding );
final String propertyName = subElement.attributeValue( "name" ); hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( collectionBinding );
attributeBinding = collectionBinding;
if ( "bag".equals( subElementName ) ) {
BagBinding bagBinding = entityBinding.makeBagAttributeBinding( propertyName );
bindCollection( subElement, bagBinding, entityBinding, PluralAttributeNature.BAG, propertyName );
hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( bagBinding );
attributeBinding = bagBinding;
} }
else if ( "idbag".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Idbag.class.isInstance( attribute ) ) {
BagBinding bagBinding = entityBinding.makeBagAttributeBinding( propertyName ); org.hibernate.metamodel.source.hbm.xml.mapping.Idbag collection = org.hibernate.metamodel.source.hbm.xml.mapping.Idbag.class.cast( attribute );
bindCollection( subElement, bagBinding, entityBinding, PluralAttributeNature.BAG, propertyName ); //BagBinding collectionBinding = entityBinding.makeBagAttributeBinding( collection.getName() );
hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( bagBinding ); //bindIdbag( collection, bagBinding, entityBinding, PluralAttributeNature.BAG, collection.getName() );
attributeBinding = bagBinding;
// todo: handle identifier // todo: handle identifier
//attributeBinding = collectionBinding;
//hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( attributeBinding );
} }
else if ( "set".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Set.class.isInstance( attribute ) ) {
BagBinding bagBinding = entityBinding.makeBagAttributeBinding( propertyName ); org.hibernate.metamodel.source.hbm.xml.mapping.Set collection = org.hibernate.metamodel.source.hbm.xml.mapping.Set.class.cast( attribute );
bindCollection( subElement, bagBinding, entityBinding, PluralAttributeNature.SET, propertyName ); //BagBinding collectionBinding = entityBinding.makeBagAttributeBinding( collection.getName() );
hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( bagBinding ); //bindSet( collection, collectionBinding, entityBinding, PluralAttributeNature.SET, collection.getName() );
attributeBinding = bagBinding; //attributeBinding = collectionBinding;
//hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( attributeBinding );
} }
else if ( "list".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.List.class.isInstance( attribute ) ) {
BagBinding bagBinding = entityBinding.makeBagAttributeBinding( propertyName ); org.hibernate.metamodel.source.hbm.xml.mapping.List collection = org.hibernate.metamodel.source.hbm.xml.mapping.List.class.cast( attribute );
bindCollection( subElement, bagBinding, entityBinding, PluralAttributeNature.LIST, propertyName ); //ListBinding collectionBinding = entityBinding.makeBagAttributeBinding( collection.getName() );
hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( bagBinding ); //bindList( collection, bagBinding, entityBinding, PluralAttributeNature.LIST, collection.getName() );
attributeBinding = bagBinding;
// todo : handle list index // todo : handle list index
//attributeBinding = collectionBinding;
//hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( attributeBinding );
} }
else if ( "map".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Map.class.isInstance( attribute ) ) {
BagBinding bagBinding = entityBinding.makeBagAttributeBinding( propertyName ); org.hibernate.metamodel.source.hbm.xml.mapping.Map collection = org.hibernate.metamodel.source.hbm.xml.mapping.Map.class.cast( attribute );
bindCollection( subElement, bagBinding, entityBinding, PluralAttributeNature.MAP, propertyName ); //BagBinding bagBinding = entityBinding.makeBagAttributeBinding( collection.getName() );
hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( bagBinding ); //bindMap( collection, bagBinding, entityBinding, PluralAttributeNature.MAP, collection.getName() );
attributeBinding = bagBinding;
// todo : handle map key // todo : handle map key
//hibernateMappingBinder.getHibernateXmlBinder().getMetadata().addCollection( attributeBinding );
} }
else if ( "many-to-one".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.ManyToOne.class.isInstance( attribute ) ) {
// todo : implement // todo : implement
// value = new ManyToOne( mappings, table ); // value = new ManyToOne( mappings, table );
// bindManyToOne( subElement, (ManyToOne) value, propertyName, nullable, mappings ); // bindManyToOne( subElement, (ManyToOne) value, propertyName, nullable, mappings );
} }
else if ( "any".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Any.class.isInstance( attribute ) ) {
// todo : implement // todo : implement
// value = new Any( mappings, table ); // value = new Any( mappings, table );
// bindAny( subElement, (Any) value, nullable, mappings ); // bindAny( subElement, (Any) value, nullable, mappings );
} }
else if ( "one-to-one".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.OneToOne.class.isInstance( attribute ) ) {
// todo : implement // todo : implement
// value = new OneToOne( mappings, table, persistentClass ); // value = new OneToOne( mappings, table, persistentClass );
// bindOneToOne( subElement, (OneToOne) value, propertyName, true, mappings ); // bindOneToOne( subElement, (OneToOne) value, propertyName, true, mappings );
} }
else if ( "property".equals( subElementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Property.class.isInstance( attribute ) ) {
SimpleAttributeBinding binding = entityBinding.makeSimpleAttributeBinding( propertyName ); org.hibernate.metamodel.source.hbm.xml.mapping.Property property = org.hibernate.metamodel.source.hbm.xml.mapping.Property.class.cast( attribute );
bindSimpleAttribute( subElement, binding, entityBinding, propertyName ); SimpleAttributeBinding binding = entityBinding.makeSimpleAttributeBinding( property.getName() );
bindSimpleAttribute( property, binding, entityBinding );
attributeBinding = binding; attributeBinding = binding;
} }
else if ( "component".equals( subElementName ) else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Component.class.isInstance( attribute )
|| "dynamic-component".equals( subElementName ) || org.hibernate.metamodel.source.hbm.xml.mapping.DynamicComponent.class.isInstance( attribute )
|| "properties".equals( subElementName ) ) { || org.hibernate.metamodel.source.hbm.xml.mapping.Properties.class.isInstance( attribute ) ) {
// todo : implement // todo : implement
// String subpath = StringHelper.qualify( entityName, propertyName ); // String subpath = StringHelper.qualify( entityName, propertyName );
// value = new Component( mappings, persistentClass ); // value = new Component( mappings, persistentClass );
@ -335,30 +337,36 @@ else if ( "component".equals( subElementName )
// false // false
// ); // );
} }
else if ( "join".equals( subElementName ) ) { }
/*
Array
PrimitiveArray
*/
for ( org.hibernate.metamodel.source.hbm.xml.mapping.Join join : entityClazz.getJoin() ) {
// todo : implement // todo : implement
// Join join = new Join(); // Join join = new Join();
// join.setPersistentClass( persistentClass ); // join.setPersistentClass( persistentClass );
// bindJoin( subElement, join, mappings, inheritedMetas ); // bindJoin( subElement, join, mappings, inheritedMetas );
// persistentClass.addJoin( join ); // persistentClass.addJoin( join );
} }
else if ( "subclass".equals( subElementName ) ) { for ( org.hibernate.metamodel.source.hbm.xml.mapping.Subclass subclass : entityClazz.getSubclass() ) {
// todo : implement // todo : implement
// handleSubclass( persistentClass, mappings, subElement, inheritedMetas ); // handleSubclass( persistentClass, mappings, subElement, inheritedMetas );
} }
else if ( "joined-subclass".equals( subElementName ) ) { for ( org.hibernate.metamodel.source.hbm.xml.mapping.JoinedSubclass subclass : entityClazz.getJoinedSubclass() ) {
// todo : implement // todo : implement
// handleJoinedSubclass( persistentClass, mappings, subElement, inheritedMetas ); // handleJoinedSubclass( persistentClass, mappings, subElement, inheritedMetas );
} }
else if ( "union-subclass".equals( subElementName ) ) { for ( org.hibernate.metamodel.source.hbm.xml.mapping.UnionSubclass subclass : entityClazz.getUnionSubclass() ) {
// todo : implement // todo : implement
// handleUnionSubclass( persistentClass, mappings, subElement, inheritedMetas ); // handleUnionSubclass( persistentClass, mappings, subElement, inheritedMetas );
} }
else if ( "filter".equals( subElementName ) ) { for ( org.hibernate.metamodel.source.hbm.xml.mapping.Filter filter : entityClazz.getFilter() ) {
// todo : implement // todo : implement
// parseFilter( subElement, entityBinding ); // parseFilter( subElement, entityBinding );
} }
else if ( "natural-id".equals( subElementName ) ) { if ( entityClazz.getNaturalId() != null ) {
// todo : implement // todo : implement
// UniqueKey uk = new UniqueKey(); // UniqueKey uk = new UniqueKey();
// uk.setName("_UniqueKey"); // uk.setName("_UniqueKey");
@ -377,19 +385,24 @@ else if ( "natural-id".equals( subElementName ) ) {
// ); // );
// table.addUniqueKey(uk); // table.addUniqueKey(uk);
} }
else if ( "query".equals(subElementName) ) { if ( entityClazz.getQueryOrSqlQuery() != null ) {
for ( Object queryOrSqlQuery : entityClazz.getQueryOrSqlQuery() ) {
if ( org.hibernate.metamodel.source.hbm.xml.mapping.Query.class.isInstance( queryOrSqlQuery ) ) {
// todo : implement // todo : implement
// bindNamedQuery(subElement, persistentClass.getEntityName(), mappings); // bindNamedQuery(subElement, persistentClass.getEntityName(), mappings);
} }
else if ( "sql-query".equals(subElementName) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.SqlQuery.class.isInstance( queryOrSqlQuery ) ) {
// todo : implement // todo : implement
// bindNamedSQLQuery(subElement, persistentClass.getEntityName(), mappings); // bindNamedSQLQuery(subElement, persistentClass.getEntityName(), mappings);
} }
else if ( "resultset".equals(subElementName) ) { }
}
if ( entityClazz.getResultset() != null ) {
for ( org.hibernate.metamodel.source.hbm.xml.mapping.Resultset resultSet : entityClazz.getResultset() ) {
// todo : implement // todo : implement
// bindResultSetMappingDefinition( subElement, persistentClass.getEntityName(), mappings ); // bindResultSetMappingDefinition( subElement, persistentClass.getEntityName(), mappings );
} }
}
// if ( value != null ) { // if ( value != null ) {
// Property property = createProperty( value, propertyName, persistentClass // Property property = createProperty( value, propertyName, persistentClass
// .getClassName(), subElement, mappings, inheritedMetas ); // .getClassName(), subElement, mappings, inheritedMetas );
@ -400,9 +413,8 @@ else if ( "resultset".equals(subElementName) ) {
// } // }
} }
}
protected void bindSimpleAttribute(Element propertyElement, protected void bindSimpleAttribute(org.hibernate.metamodel.source.hbm.xml.mapping.Id id,
SimpleAttributeBinding attributeBinding, SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding, EntityBinding entityBinding,
String attributeName) { String attributeName) {
@ -410,8 +422,9 @@ protected void bindSimpleAttribute(Element propertyElement,
attributeBinding.initialize( attributeBinding.initialize(
new HbmSimpleAttributeDomainState( new HbmSimpleAttributeDomainState(
hibernateMappingBinder, hibernateMappingBinder,
propertyElement, entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ),
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ) entityBinding.getMetaAttributes(),
id
) )
); );
} }
@ -422,26 +435,139 @@ protected void bindSimpleAttribute(Element propertyElement,
attributeBinding.initializeTupleValue( attributeBinding.initializeTupleValue(
new HbmSimpleValueRelationalStateContainer( new HbmSimpleValueRelationalStateContainer(
getHibernateMappingBinder(), getHibernateMappingBinder(),
propertyElement, true,
true id
) )
); );
} }
} }
protected void bindCollection( protected void bindSimpleAttribute(org.hibernate.metamodel.source.hbm.xml.mapping.Discriminator discriminator,
Element collectionNode, SimpleAttributeBinding attributeBinding,
PluralAttributeBinding collectionBinding,
EntityBinding entityBinding, EntityBinding entityBinding,
PluralAttributeNature attributeNature,
String attributeName) { String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
hibernateMappingBinder,
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName ),
entityBinding.getMetaAttributes(),
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 void bindSimpleAttribute(org.hibernate.metamodel.source.hbm.xml.mapping.Version version,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding,
String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
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(org.hibernate.metamodel.source.hbm.xml.mapping.Timestamp timestamp,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding,
String attributeName) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
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(org.hibernate.metamodel.source.hbm.xml.mapping.Property property,
SimpleAttributeBinding attributeBinding,
EntityBinding entityBinding) {
if ( attributeBinding.getAttribute() == null ) {
attributeBinding.initialize(
new HbmSimpleAttributeDomainState(
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(
org.hibernate.metamodel.source.hbm.xml.mapping.Bag collection,
PluralAttributeBinding collectionBinding,
EntityBinding entityBinding) {
if ( collectionBinding.getAttribute() == null ) { if ( collectionBinding.getAttribute() == null ) {
// domain model has not been bound yet // domain model has not been bound yet
collectionBinding.initialize( collectionBinding.initialize(
new HbmPluralAttributeDomainState( new HbmPluralAttributeDomainState(
hibernateMappingBinder, hibernateMappingBinder,
collectionNode, collection,
entityBinding.getEntity().getOrCreatePluralAttribute( attributeName, attributeNature ) entityBinding.getMetaAttributes(),
entityBinding.getEntity().getOrCreatePluralAttribute(
collection.getName(),
PluralAttributeNature.BAG
)
) )
); );
} }

View File

@ -25,6 +25,7 @@
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map; import java.util.Map;
import org.dom4j.Attribute; import org.dom4j.Attribute;
@ -33,9 +34,10 @@
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.engine.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.ExecuteUpdateResultCheckStyle;
import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.metamodel.binding.CustomSQL; import org.hibernate.metamodel.binding.CustomSQL;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.source.util.DomHelper;
import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* TODO : javadoc * TODO : javadoc
@ -58,58 +60,43 @@ public static boolean isCallable(Element element, boolean supportsCallable) {
return false; return false;
} }
public static ExecuteUpdateResultCheckStyle getResultCheckStyle(Element element, boolean callable) { public static ExecuteUpdateResultCheckStyle getResultCheckStyle(String check, boolean callable) {
Attribute attr = element.attribute( "check" ); if ( check == null ) {
if ( attr == null ) {
// use COUNT as the default. This mimics the old behavior, although // use COUNT as the default. This mimics the old behavior, although
// NONE might be a better option moving forward in the case of callable // NONE might be a better option moving forward in the case of callable
return ExecuteUpdateResultCheckStyle.COUNT; return ExecuteUpdateResultCheckStyle.COUNT;
} }
return ExecuteUpdateResultCheckStyle.parse( attr.getValue() ); return ExecuteUpdateResultCheckStyle.parse( check );
} }
public static final Map<String, MetaAttribute> extractMetas(Element node, Map<String, MetaAttribute> baseline) { public static final Map<String, MetaAttribute> extractMetas(List<org.hibernate.metamodel.source.hbm.xml.mapping.Meta> meta, Map<String, MetaAttribute> baseline) {
return extractMetas( node, false, baseline ); return extractMetas( meta, false, baseline );
} }
public static final Map<String, MetaAttribute> extractMetas(Element node, boolean onlyInheritable, Map<String, MetaAttribute> baseline) { public static final Map<String, MetaAttribute> extractMetas(List<org.hibernate.metamodel.source.hbm.xml.mapping.Meta> metaList, boolean onlyInheritable, Map<String, MetaAttribute> baseline) {
Map<String, MetaAttribute> extractedMetas = new HashMap<String, MetaAttribute>(); Map<String, MetaAttribute> extractedMetas = new HashMap<String, MetaAttribute>();
extractedMetas.putAll( baseline ); extractedMetas.putAll( baseline );
for ( org.hibernate.metamodel.source.hbm.xml.mapping.Meta meta : metaList) {
Iterator iter = node.elementIterator( "meta" ); boolean inheritable = Boolean.valueOf( meta.getInherit() );
while ( iter.hasNext() ) {
Element metaNode = (Element) iter.next();
boolean inheritable = Boolean.valueOf( metaNode.attributeValue( "inherit" ) ).booleanValue();
if ( onlyInheritable & !inheritable ) { if ( onlyInheritable & !inheritable ) {
continue; continue;
} }
final String name = metaNode.attributeValue( "attribute" ); final String name = meta.getAttribute();
final MetaAttribute inheritedMetaAttribute = (MetaAttribute) baseline.get( name ); final MetaAttribute inheritedMetaAttribute = baseline.get( name );
MetaAttribute metaAttribute = (MetaAttribute) extractedMetas.get( name ); MetaAttribute metaAttribute = extractedMetas.get( name );
if ( metaAttribute == null || metaAttribute == inheritedMetaAttribute ) { if ( metaAttribute == null || metaAttribute == inheritedMetaAttribute ) {
metaAttribute = new MetaAttribute( name ); metaAttribute = new MetaAttribute( name );
extractedMetas.put( name, metaAttribute ); extractedMetas.put( name, metaAttribute );
} }
metaAttribute.addValue( metaNode.getText() ); metaAttribute.addValue( meta.getContent() );
} }
return extractedMetas; return extractedMetas;
} }
public static String getSubselect(Element element) { public static String extractEntityName( org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz, String unqualifiedPackageName) {
String subselect = element.attributeValue( "subselect" ); String entityName = entityClazz.getEntityName();
if ( subselect != null ) { return entityName == null ? getClassName( entityClazz.getName(), unqualifiedPackageName ) : entityName;
return subselect;
}
else {
Element subselectElement = element.element( "subselect" );
return subselectElement == null ? null : subselectElement.getText();
}
}
public static String extractEntityName(Element elem, String unqualifiedPackageName) {
String entityName = elem.attributeValue( "entity-name" );
return entityName == null ? getClassName( elem.attribute( "name" ), unqualifiedPackageName ) : entityName;
} }
public static String getClassName(Attribute att, String unqualifiedPackageName) { public static String getClassName(Attribute att, String unqualifiedPackageName) {
@ -127,12 +114,8 @@ public static String getClassName(String unqualifiedName, String unqualifiedPack
return unqualifiedName; return unqualifiedName;
} }
public static CustomSQL getCustomSql(Element element ) { public static CustomSQL getCustomSql(String sql, boolean isCallable, String check ) {
if ( element == null ) { return new CustomSQL( sql.trim(), isCallable, getResultCheckStyle( check, isCallable ) );
return null; // EARLY EXIT!!!
}
boolean callable = DomHelper.extractBooleanAttributeValue( element, "callable", false );
return new CustomSQL( element.getTextTrim(), callable, getResultCheckStyle( element, callable ) );
} }
public static String getPropertyAccessorName(Element element, boolean isEmbedded, String defaultAccess) { public static String getPropertyAccessorName(Element element, boolean isEmbedded, String defaultAccess) {
@ -142,4 +125,11 @@ public static String getPropertyAccessorName(Element element, boolean isEmbedded
isEmbedded ? "embedded" : defaultAccess isEmbedded ? "embedded" : defaultAccess
); );
} }
public static String getPropertyAccessorName(String access, boolean isEmbedded, String defaultAccess) {
return MappingHelper.getStringValue(
access,
isEmbedded ? "embedded" : defaultAccess
);
}
} }

View File

@ -23,29 +23,29 @@
*/ */
package org.hibernate.metamodel.source.hbm; package org.hibernate.metamodel.source.hbm;
import java.util.Iterator; import java.util.List;
import java.util.Map; import java.util.Map;
import org.dom4j.Attribute; import org.dom4j.Attribute;
import org.dom4j.Element;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.mapping.FetchProfile;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.MetadataSource; import org.hibernate.mapping.MetadataSource;
import org.hibernate.metamodel.binding.MappingDefaults; import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.Origin;
import org.hibernate.metamodel.source.internal.JaxbRoot;
import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* Responsible for performing binding of the {@code <hibernate-mapping/>} DOM element * Responsible for performing binding of the {@code <hibernate-mapping/>} DOM element
*/ */
class HibernateMappingBinder implements MappingDefaults { class HibernateMappingBinder implements MappingDefaults {
private final HibernateXmlBinder hibernateXmlBinder; private final HibernateXmlBinder hibernateXmlBinder;
private final XmlDocument xmlDocument; private final JaxbRoot<HibernateMapping> jaxbRoot;
private final Element hibernateMappingElement; private final HibernateMapping hibernateMapping;
private final String defaultSchemaName; private final String defaultSchemaName;
private final String defaultCatalogName; private final String defaultCatalogName;
@ -57,28 +57,34 @@ class HibernateMappingBinder implements MappingDefaults {
private Map<String, MetaAttribute> mappingMetas; private Map<String, MetaAttribute> mappingMetas;
HibernateMappingBinder(HibernateXmlBinder hibernateXmlBinder, XmlDocument xmlDocument) {
HibernateMappingBinder(HibernateXmlBinder hibernateXmlBinder, JaxbRoot<HibernateMapping> jaxbRoot) {
this.hibernateXmlBinder = hibernateXmlBinder; this.hibernateXmlBinder = hibernateXmlBinder;
this.xmlDocument = xmlDocument; this.jaxbRoot = jaxbRoot;
this.hibernateMappingElement = xmlDocument.getDocumentTree().getRootElement(); this.hibernateMapping = jaxbRoot.getRoot();
defaultSchemaName = DomHelper.extractAttributeValue( hibernateMappingElement, "schema" ); defaultSchemaName = hibernateMapping.getSchema();
defaultCatalogName = DomHelper.extractAttributeValue( hibernateMappingElement, "catalog" ); defaultCatalogName = hibernateMapping.getCatalog();
defaultCascade = DomHelper.extractAttributeValue( hibernateMappingElement, "default-cascade", "none" ); defaultCascade = MappingHelper.getStringValue( hibernateMapping.getDefaultCascade(), "none" );
defaultAccess = DomHelper.extractAttributeValue( hibernateMappingElement, "default-access", "property" ); defaultAccess = MappingHelper.getStringValue( hibernateMapping.getDefaultAccess(), "property" );
defaultLazy = "true".equals( DomHelper.extractAttributeValue( hibernateMappingElement, "default-lazy", "false" ) ); //TODO: shouldn't default-lazy default to true???
packageName = DomHelper.extractAttributeValue( hibernateMappingElement, "package" ); defaultLazy = MappingHelper.getBooleanValue( hibernateMapping.getDefaultLazy(), false );
autoImport = "true".equals( DomHelper.extractAttributeValue( hibernateMappingElement, "auto-import", "false" ) ); packageName = hibernateMapping.getPackage();
autoImport = MappingHelper.getBooleanValue( hibernateMapping.getAutoImport(), false );
mappingMetas = HbmHelper.extractMetas( hibernateMappingElement, true, hibernateXmlBinder.getGlobalMetas() ); mappingMetas = HbmHelper.extractMetas( hibernateMapping.getMeta(), true, hibernateXmlBinder.getGlobalMetas() );
} }
HibernateXmlBinder getHibernateXmlBinder() { HibernateXmlBinder getHibernateXmlBinder() {
return hibernateXmlBinder; return hibernateXmlBinder;
} }
XmlDocument getXmlDocument() { HibernateMapping getHibernateMapping() {
return xmlDocument; return hibernateMapping;
}
Origin getOrigin() {
return jaxbRoot.getOrigin();
} }
public String getDefaultSchemaName() { public String getDefaultSchemaName() {
@ -117,85 +123,96 @@ public Map<String, MetaAttribute> getMappingMetas() {
return mappingMetas; return mappingMetas;
} }
void processElement() { void processHibernateMapping() {
Iterator rootChildren = hibernateMappingElement.elementIterator(); if ( hibernateMapping.getFilterDef() != null ) {
while ( rootChildren.hasNext() ) { // parseFilterDefs( hibernateMapping.getFilterDef() );
final Element element = (Element) rootChildren.next();
final String elementName = element.getName();
if ( "filter-def".equals( elementName ) ) {
// parseFilterDef( element, mappings );
} }
else if ( "fetch-profile".equals( elementName ) ) { if ( hibernateMapping.getFetchProfile() != null ) {
parseFetchProfile( element, null ); parseFetchProfiles( hibernateMapping.getFetchProfile(), null );
} }
else if ( "identifier-generator".equals( elementName ) ) { if ( hibernateMapping.getIdentifierGenerator() != null ) {
// parseIdentifierGeneratorRegistration( element, mappings ); // parseIdentifierGeneratorRegistrations( hibernateMapping.getIdentifierGenerator() );
} }
else if ( "typedef".equals( elementName ) ) { if ( hibernateMapping.getTypedef() != null ) {
// bindTypeDef( element, mappings ); // bindTypeDef( hibernateMapping.getTypedefs() );
} }
else if ( "class".equals( elementName ) ) { if ( hibernateMapping.getClazzOrSubclassOrJoinedSubclass() != null ) {
new RootEntityBinder( this, element ).process( element ); for ( Object clazzOrSubclass : hibernateMapping.getClazzOrSubclassOrJoinedSubclass() ) {
if ( org.hibernate.metamodel.source.hbm.xml.mapping.Class.class.isInstance( clazzOrSubclass ) ) {
org.hibernate.metamodel.source.hbm.xml.mapping.Class clazz =
org.hibernate.metamodel.source.hbm.xml.mapping.Class.class.cast( clazzOrSubclass );
new RootEntityBinder( this, clazz ).process( clazz );
} }
else if ( "subclass".equals( elementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Subclass.class.isInstance( clazzOrSubclass ) ) {
// PersistentClass superModel = getSuperclass( mappings, element ); // PersistentClass superModel = getSuperclass( mappings, element );
// handleSubclass( superModel, mappings, element, inheritedMetas ); // handleSubclass( superModel, mappings, element, inheritedMetas );
} }
else if ( "joined-subclass".equals( elementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.JoinedSubclass.class.isInstance( clazzOrSubclass ) ) {
// PersistentClass superModel = getSuperclass( mappings, element ); // PersistentClass superModel = getSuperclass( mappings, element );
// handleJoinedSubclass( superModel, mappings, element, inheritedMetas ); // handleJoinedSubclass( superModel, mappings, element, inheritedMetas );
} }
else if ( "union-subclass".equals( elementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.UnionSubclass.class.isInstance( clazzOrSubclass ) ) {
// PersistentClass superModel = getSuperclass( mappings, element ); // PersistentClass superModel = getSuperclass( mappings, element );
// handleUnionSubclass( superModel, mappings, element, inheritedMetas ); // handleUnionSubclass( superModel, mappings, element, inheritedMetas );
} }
else if ( "query".equals( elementName ) ) { else {
throw new org.hibernate.metamodel.source.MappingException( "unknown type of class or subclass: " +
clazzOrSubclass.getClass().getName(), jaxbRoot.getOrigin()
);
}
}
}
if ( hibernateMapping.getQueryOrSqlQuery() != null ) {
for ( Object queryOrSqlQuery : hibernateMapping.getQueryOrSqlQuery() ) {
if ( org.hibernate.metamodel.source.hbm.xml.mapping.Query.class.isInstance( queryOrSqlQuery ) ) {
// bindNamedQuery( element, null, mappings ); // bindNamedQuery( element, null, mappings );
} }
else if ( "sql-query".equals( elementName ) ) { else if ( org.hibernate.metamodel.source.hbm.xml.mapping.SqlQuery.class.isInstance( queryOrSqlQuery ) ) {
// bindNamedSQLQuery( element, null, mappings ); // bindNamedSQLQuery( element, null, mappings );
} }
else if ( "resultset".equals( elementName ) ) { else {
// bindResultSetMappingDefinition( element, null, mappings ); throw new org.hibernate.metamodel.source.MappingException( "unknown type of query: " +
queryOrSqlQuery.getClass().getName(), jaxbRoot.getOrigin()
);
} }
else if ( "import".equals( elementName ) ) {
processImport( element );
} }
else if ( "database-object".equals( elementName ) ) {
// bindAuxiliaryDatabaseObject( element, mappings );
} }
if ( hibernateMapping.getResultset() != null ) {
// bindResultSetMappingDefinitions( element, null, mappings );
}
if ( hibernateMapping.getImport() != null ) {
processImports( hibernateMapping.getImport() );
}
if ( hibernateMapping.getDatabaseObject() != null ) {
// bindAuxiliaryDatabaseObjects( element, mappings );
} }
} }
private void processImport(Element importNode) { private void processImports(List<org.hibernate.metamodel.source.hbm.xml.mapping.Import> imports) {
String className = getClassName( importNode.attribute( "class" ) ); for ( org.hibernate.metamodel.source.hbm.xml.mapping.Import importValue : imports ) {
Attribute renameNode = importNode.attribute( "rename" ); String className = getClassName( importValue.getClazz() );
String rename = ( renameNode == null ) ? StringHelper.unqualify( className ) : renameNode.getValue(); String rename = importValue.getRename();
rename = ( rename == null ) ? StringHelper.unqualify( className ) : rename;
hibernateXmlBinder.getMetadata().addImport( className, rename ); hibernateXmlBinder.getMetadata().addImport( className, rename );
} }
}
protected void parseFetchProfile(Element element, String containingEntityName) { protected void parseFetchProfiles(List<org.hibernate.metamodel.source.hbm.xml.mapping.FetchProfile> fetchProfiles, String containingEntityName) {
String profileName = element.attributeValue( "name" ); for ( org.hibernate.metamodel.source.hbm.xml.mapping.FetchProfile fetchProfile : fetchProfiles ) {
FetchProfile profile = hibernateXmlBinder.getMetadata().findOrCreateFetchProfile( profileName, MetadataSource.HBM ); String profileName = fetchProfile.getName();
Iterator itr = element.elementIterator( "fetch" ); org.hibernate.metamodel.binding.FetchProfile profile = hibernateXmlBinder.getMetadata().findOrCreateFetchProfile( profileName, MetadataSource.HBM );
while ( itr.hasNext() ) { for ( org.hibernate.metamodel.source.hbm.xml.mapping.Fetch fetch : fetchProfile.getFetch() ) {
final Element fetchElement = ( Element ) itr.next(); String entityName = fetch.getEntity() == null ? containingEntityName : fetch.getEntity();
final String association = fetchElement.attributeValue( "association" );
final String style = fetchElement.attributeValue( "style" );
String entityName = fetchElement.attributeValue( "entity" );
if ( entityName == null ) { if ( entityName == null ) {
entityName = containingEntityName; throw new MappingException( "could not determine entity for fetch-profile fetch [" + profileName + "]:[" + fetch.getAssociation() + "]" );
} }
if ( entityName == null ) { profile.addFetch( entityName, fetch.getAssociation(), fetch.getStyle() );
throw new MappingException( "could not determine entity for fetch-profile fetch [" + profileName + "]:[" + association + "]" );
} }
profile.addFetch( entityName, association, style );
} }
} }
String extractEntityName(Element element) { String extractEntityName( org.hibernate.metamodel.source.hbm.xml.mapping.Class entityClazz) {
return HbmHelper.extractEntityName( element, packageName ); return HbmHelper.extractEntityName( entityClazz, packageName );
} }
String getClassName(Attribute attribute) { String getClassName(Attribute attribute) {

View File

@ -21,31 +21,18 @@
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.metamodel.source.hbm.state.relational; package org.hibernate.metamodel.source.hbm;
import java.util.Set; import org.hibernate.metamodel.source.Origin;
import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
import org.dom4j.Element; import org.hibernate.metamodel.source.internal.JaxbRoot;
import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.relational.Size;
import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.source.util.DomHelper;
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class HbmRelationalState { public class HibernateMappingJaxbRoot extends JaxbRoot<HibernateMapping> {
private final Element element;
public HbmRelationalState(Element element) { public HibernateMappingJaxbRoot(HibernateMapping root, Origin origin) {
this.element = element; super(root, origin);
}
protected Element getElement() {
return element;
} }
} }

View File

@ -35,11 +35,11 @@
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.hibernate.cfg.ExtendsQueueEntry;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.mapping.MetaAttribute; 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.internal.MetadataImpl;
import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping; import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
@ -63,17 +63,13 @@ public HibernateXmlBinder(MetadataImpl metadata, Map<String, MetaAttribute> glob
this.globalMetas = globalMetas; this.globalMetas = globalMetas;
} }
public void bindRoot(XmlDocument metadataXml) { public void bindRoot(JaxbRoot<HibernateMapping> jaxbRoot) {
bindRoot( metadataXml, Collections.<String>emptySet() ); log.debug( jaxbRoot.toString() );
bindRoot( jaxbRoot, Collections.<String>emptySet() );
} }
public void bindRoot(HibernateMapping mapping) { public void bindRoot(JaxbRoot<HibernateMapping> jaxbRoot, Set<String> entityNames) {
// todo - process the mapping final HibernateMappingBinder mappingBinder = new HibernateMappingBinder( this, jaxbRoot );
log.debug( mapping.toString() );
}
public void bindRoot(XmlDocument metadataXml, Set<String> entityNames) {
final HibernateMappingBinder mappingBinder = new HibernateMappingBinder( this, metadataXml );
// this is irrelevant due to HHH-6118 and the fact that now all sources should be // this is irrelevant due to HHH-6118 and the fact that now all sources should be
// List<String> names = locateEntityNamesAwaitingExtends( metadataXml, mappingBinder ); // List<String> names = locateEntityNamesAwaitingExtends( metadataXml, mappingBinder );
@ -86,7 +82,7 @@ public void bindRoot(XmlDocument metadataXml, Set<String> entityNames) {
// return; // return;
// } // }
mappingBinder.processElement(); mappingBinder.processHibernateMapping();
} }
MetadataImpl getMetadata() { MetadataImpl getMetadata() {

View File

@ -37,7 +37,7 @@
import org.hibernate.metamodel.relational.Identifier; import org.hibernate.metamodel.relational.Identifier;
import org.hibernate.metamodel.relational.InLineView; import org.hibernate.metamodel.relational.InLineView;
import org.hibernate.metamodel.relational.Schema; import org.hibernate.metamodel.relational.Schema;
import org.hibernate.metamodel.relational.Value; import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* TODO : javadoc * TODO : javadoc
@ -46,55 +46,53 @@
*/ */
class RootEntityBinder extends AbstractEntityBinder { class RootEntityBinder extends AbstractEntityBinder {
RootEntityBinder(HibernateMappingBinder hibernateMappingBinder, Element entityElement) { RootEntityBinder(HibernateMappingBinder hibernateMappingBinder, org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlClazz) {
super( hibernateMappingBinder, entityElement ); super( hibernateMappingBinder, xmlClazz );
} }
public void process(Element entityElement) { public void process(org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlClazz) {
String entityName = getHibernateMappingBinder().extractEntityName( entityElement ); String entityName = getHibernateMappingBinder().extractEntityName( xmlClazz );
if ( entityName == null ) { if ( entityName == null ) {
throw new MappingException( "Unable to determine entity name" ); throw new MappingException( "Unable to determine entity name" );
} }
EntityBinding entityBinding = new EntityBinding(); EntityBinding entityBinding = new EntityBinding();
basicEntityBinding( entityElement, entityBinding, null ); basicEntityBinding( xmlClazz, entityBinding, null );
basicTableBinding( entityElement, entityBinding ); basicTableBinding( xmlClazz, entityBinding );
Attribute mutableAttribute = entityElement.attribute( "mutable" ); if ( xmlClazz.getMutable() != null ) {
if ( mutableAttribute != null ) { entityBinding.setMutable( Boolean.valueOf( xmlClazz.getMutable() ) );
entityBinding.setMutable( Boolean.valueOf( mutableAttribute.getValue() ) );
} }
Attribute whereAttribute = entityElement.attribute( "where" ); if ( xmlClazz.getWhere() != null ) {
if ( whereAttribute != null ) { entityBinding.setWhereFilter( xmlClazz.getWhere() );
entityBinding.setWhereFilter( whereAttribute.getValue() );
} }
Attribute polymorphismAttribute = entityElement.attribute( "polymorphism" ); if ( xmlClazz.getPolymorphism() != null ) {
if ( polymorphismAttribute != null ) { entityBinding.setExplicitPolymorphism( "explicit".equals( xmlClazz.getPolymorphism() ) );
entityBinding.setExplicitPolymorphism( "explicit".equals( polymorphismAttribute.getValue() ) );
} }
Attribute rowidAttribute = entityElement.attribute( "rowid" ); if ( xmlClazz.getRowid() != null ) {
if ( rowidAttribute != null ) { entityBinding.setRowId( xmlClazz.getRowid() );
entityBinding.setRowId( rowidAttribute.getValue() );
} }
bindIdentifier( entityElement, entityBinding ); bindIdentifier( xmlClazz, entityBinding );
bindDiscriminator( entityElement, entityBinding ); bindDiscriminator( xmlClazz, entityBinding );
bindVersion( entityElement, entityBinding ); bindVersion( xmlClazz, entityBinding );
bindCaching( entityElement, entityBinding ); bindCaching( xmlClazz, entityBinding );
// called createClassProperties in HBMBinder... // called createClassProperties in HBMBinder...
buildAttributeBindings( entityElement, entityBinding ); buildAttributeBindings( xmlClazz, entityBinding );
getHibernateXmlBinder().getMetadata().addEntity( entityBinding ); getHibernateXmlBinder().getMetadata().addEntity( entityBinding );
} }
private void basicTableBinding(Element entityElement, EntityBinding entityBinding) { private void basicTableBinding(org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlClazz,
EntityBinding entityBinding) {
final Schema schema = getHibernateXmlBinder().getMetadata().getDatabase().getSchema( getSchemaName() ); final Schema schema = getHibernateXmlBinder().getMetadata().getDatabase().getSchema( getSchemaName() );
final String subSelect = HbmHelper.getSubselect( entityElement ); final String subSelect =
xmlClazz.getSubselect() == null ? xmlClazz.getSubselectElement() : xmlClazz.getSubselect();
if ( subSelect != null ) { if ( subSelect != null ) {
final String logicalName = entityBinding.getEntity().getName(); final String logicalName = entityBinding.getEntity().getName();
InLineView inLineView = schema.getInLineView( logicalName ); InLineView inLineView = schema.getInLineView( logicalName );
@ -104,50 +102,46 @@ private void basicTableBinding(Element entityElement, EntityBinding entityBindin
entityBinding.setBaseTable( inLineView ); entityBinding.setBaseTable( inLineView );
} }
else { else {
final Identifier tableName = Identifier.toIdentifier( getClassTableName( entityElement, entityBinding, null ) ); final Identifier tableName = Identifier.toIdentifier( getClassTableName( xmlClazz, entityBinding, null ) );
org.hibernate.metamodel.relational.Table table = schema.getTable( tableName ); org.hibernate.metamodel.relational.Table table = schema.getTable( tableName );
if ( table == null ) { if ( table == null ) {
table = schema.createTable( tableName ); table = schema.createTable( tableName );
} }
entityBinding.setBaseTable( table ); entityBinding.setBaseTable( table );
Element comment = entityElement.element( "comment" ); String comment = xmlClazz.getComment();
if ( comment != null ) { if ( comment != null ) {
table.addComment( comment.getTextTrim() ); table.addComment( comment.trim() );
} }
Attribute checkAttribute = entityElement.attribute( "check" ); String check = xmlClazz.getCheck();
if ( checkAttribute != null ) { if ( check != null ) {
table.addCheckConstraint( checkAttribute.getValue() ); table.addCheckConstraint( check );
} }
} }
} }
private void bindIdentifier(Element entityElement, EntityBinding entityBinding) { private void bindIdentifier(org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlClazz,
final Element idElement = entityElement.element( "id" ); EntityBinding entityBinding) {
if ( idElement != null ) { if ( xmlClazz.getId() != null ) {
bindSimpleId( idElement, entityBinding ); bindSimpleId( xmlClazz.getId(), entityBinding );
return; return;
} }
final Element compositeIdElement = entityElement.element( "composite-id" ); if ( xmlClazz.getCompositeId() != null ) {
if ( compositeIdElement != null ) { bindCompositeId( xmlClazz.getCompositeId(), entityBinding );
bindCompositeId( compositeIdElement, entityBinding );
} }
throw new InvalidMappingException( throw new InvalidMappingException(
"Entity [" + entityBinding.getEntity().getName() + "] did not contain identifier mapping", "Entity [" + entityBinding.getEntity().getName() + "] did not contain identifier mapping",
getHibernateMappingBinder().getXmlDocument() getHibernateMappingBinder().getOrigin()
); );
} }
private void bindSimpleId(Element identifierElement, EntityBinding entityBinding) { private void bindSimpleId(org.hibernate.metamodel.source.hbm.xml.mapping.Id id, EntityBinding entityBinding) {
// Handle the domain portion of the binding... // Handle the domain portion of the binding...
final String explicitName = identifierElement.attributeValue( "name" ); final String explicitName = id.getName();
final String attributeName = explicitName == null ? RootClass.DEFAULT_IDENTIFIER_COLUMN_NAME : explicitName; final String attributeName = explicitName == null ? RootClass.DEFAULT_IDENTIFIER_COLUMN_NAME : explicitName;
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName );
SimpleAttributeBinding idBinding = entityBinding.makeSimplePrimaryKeyAttributeBinding( attributeName ); SimpleAttributeBinding idBinding = entityBinding.makeSimplePrimaryKeyAttributeBinding( attributeName );
bindSimpleAttribute( id, idBinding, entityBinding, attributeName );
bindSimpleAttribute( identifierElement, idBinding, entityBinding, attributeName );
if ( ! Column.class.isInstance( idBinding.getValue() ) ) { if ( ! Column.class.isInstance( idBinding.getValue() ) ) {
// this should never ever happen.. // this should never ever happen..
@ -205,8 +199,8 @@ private void bindSimpleId(Element identifierElement, EntityBinding entityBinding
// makeIdentifier( idNode, id, mappings ); // makeIdentifier( idNode, id, mappings );
} }
private static void bindCompositeId(Element identifierElement, EntityBinding entityBinding) { private static void bindCompositeId(org.hibernate.metamodel.source.hbm.xml.mapping.CompositeId compositeId, EntityBinding entityBinding) {
final String explicitName = identifierElement.attributeValue( "name" ); final String explicitName = compositeId.getName();
// String propertyName = idNode.attributeValue( "name" ); // String propertyName = idNode.attributeValue( "name" );
// Component id = new Component( mappings, entity ); // Component id = new Component( mappings, entity );
@ -235,83 +229,60 @@ private static void bindCompositeId(Element identifierElement, EntityBinding ent
} }
private void bindDiscriminator(Element entityElement, EntityBinding entityBinding) { private void bindDiscriminator(org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlEntityClazz,
Element discriminatorElement = entityElement.element( "discriminator" ); EntityBinding entityBinding) {
if ( discriminatorElement == null ) { if ( xmlEntityClazz.getDiscriminator() == null ) {
return; return;
} }
final String explicitName = discriminatorElement.attributeValue( "name" ); // Discriminator.getName() is not defined, so the attribute will always be RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME
final String attributeName = explicitName == null ? RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME : explicitName; SimpleAttributeBinding discriminatorBinding = entityBinding.makeEntityDiscriminatorBinding( RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME );
entityBinding.getEntity().getOrCreateSingularAttribute( attributeName );
SimpleAttributeBinding discriminatorBinding = entityBinding.makeEntityDiscriminatorBinding( attributeName );
// Handle the relational portion of the binding... // Handle the relational portion of the binding...
bindSimpleAttribute( discriminatorElement, discriminatorBinding, entityBinding, attributeName ); bindSimpleAttribute( xmlEntityClazz.getDiscriminator(), discriminatorBinding, entityBinding, RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME );
if ( discriminatorBinding.getHibernateTypeDescriptor().getTypeName() == null ) {
discriminatorBinding.getHibernateTypeDescriptor().setTypeName( "string" ); entityBinding.getEntityDiscriminator().setForced( MappingHelper.getBooleanValue( xmlEntityClazz.getDiscriminator().getForce(), false ) );
} }
if ( "true".equals( discriminatorElement.attributeValue( "force" ) ) ) { private void bindVersion(org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlEntityClazz,
entityBinding.getEntityDiscriminator().setForced( true ); EntityBinding entityBinding) {
} if ( xmlEntityClazz.getVersion() == null && xmlEntityClazz.getTimestamp() == null ) {
if ( "false".equals( discriminatorElement.attributeValue( "insert" ) ) ) {
entityBinding.getEntityDiscriminator().setInserted( false );
}
}
private void bindVersion(Element entityElement, EntityBinding entityBinding) {
Element versioningElement = entityElement.element( "version" );
if ( versioningElement == null ) {
versioningElement = entityElement.element( "timestamp" );
}
if ( versioningElement == null ) {
return; return;
} }
boolean isVersion = "version".equals( versioningElement.getName() ); boolean isVersion = xmlEntityClazz.getVersion() != null;
String explicitName = isVersion ? xmlEntityClazz.getVersion().getName() : xmlEntityClazz.getTimestamp().getName();
final String explicitName = versioningElement.attributeValue( "name" );
if ( explicitName == null ) { if ( explicitName == null ) {
throw new MappingException( "Mising property name for version/timestamp mapping [" + entityBinding.getEntity().getName() + "]" ); throw new MappingException( "Mising property name for version/timestamp mapping [" + entityBinding.getEntity().getName() + "]" );
} }
entityBinding.getEntity().getOrCreateSingularAttribute( explicitName );
SimpleAttributeBinding versionBinding = entityBinding.makeVersionBinding( explicitName ); SimpleAttributeBinding versionBinding = entityBinding.makeVersionBinding( explicitName );
bindSimpleAttribute( versioningElement, versionBinding, entityBinding, explicitName );
if ( versionBinding.getHibernateTypeDescriptor().getTypeName() == null ) {
if ( isVersion ) { if ( isVersion ) {
versionBinding.getHibernateTypeDescriptor().setTypeName( "integer" ); bindSimpleAttribute(
xmlEntityClazz.getVersion(),
versionBinding,
entityBinding,
explicitName
);
} }
else { else {
final String tsSource = versioningElement.attributeValue( "source" ); bindSimpleAttribute(
if ( "db".equals( tsSource ) ) { xmlEntityClazz.getTimestamp(),
versionBinding.getHibernateTypeDescriptor().setTypeName( "dbtimestamp" ); versionBinding,
} entityBinding,
else { explicitName
versionBinding.getHibernateTypeDescriptor().setTypeName( "timestamp" ); );
}
} }
} }
// for version properties marked as being generated, make sure they are "always" private void bindCaching(org.hibernate.metamodel.source.hbm.xml.mapping.Class xmlClazz,
// generated; aka, "insert" is invalid; this is dis-allowed by the DTD, EntityBinding entityBinding) {
// but just to make sure... org.hibernate.metamodel.source.hbm.xml.mapping.Cache cache = xmlClazz.getCache();
if ( versionBinding.getGeneration() == PropertyGeneration.INSERT ) { if ( cache == null ) {
throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
}
}
private void bindCaching(Element entityElement, EntityBinding entityBinding) {
final Element cacheElement = entityElement.element( "cache" );
if ( cacheElement == null ) {
return; return;
} }
final String explicitRegion = cacheElement.attributeValue( "region" ); final String region = cache.getRegion() != null ? cache.getRegion() : entityBinding.getEntity().getName();
final String region = explicitRegion != null ? explicitRegion : entityBinding.getEntity().getName(); final String strategy = cache.getUsage();
final String strategy = cacheElement.attributeValue( "usage" ); final boolean cacheLazyProps = !"non-lazy".equals( cache.getInclude() );
final boolean cacheLazyProps = !"non-lazy".equals( cacheElement.attributeValue( "include" ) );
entityBinding.setCaching( new Caching( region, strategy, cacheLazyProps ) ); entityBinding.setCaching( new Caching( region, strategy, cacheLazyProps ) );
} }

View File

@ -25,49 +25,148 @@
import java.util.Map; import java.util.Map;
import org.dom4j.Element;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.metamodel.binding.AbstractAttributeBinding; import org.hibernate.metamodel.binding.AbstractAttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding; import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor; import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.binding.MappingDefaults; import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.domain.Attribute; import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.hbm.HbmHelper; import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public abstract class AbstractHbmAttributeDomainState implements AbstractAttributeBinding.DomainState { public abstract class AbstractHbmAttributeDomainState implements AbstractAttributeBinding.DomainState {
private final MappingDefaults defaults; private final MappingDefaults defaults;
private final Element element;
private final Attribute attribute; private final Attribute attribute;
private final HibernateTypeDescriptor hibernateTypeDescriptor;
private final String accessorName;
private final String cascade;
private final boolean isOptimisticLockable;
private final String nodeName;
private final Map<String, MetaAttribute> metaAttributes;
public AbstractHbmAttributeDomainState(MappingDefaults defaults, public AbstractHbmAttributeDomainState(MappingDefaults defaults,
Element element, Attribute attribute,
Attribute attribute) { Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Id id) {
this.defaults = defaults; this.defaults = defaults;
this.element = element;
this.attribute = attribute; this.attribute = attribute;
this.hibernateTypeDescriptor = new HibernateTypeDescriptor();
this.hibernateTypeDescriptor.setTypeName( id.getType() );
this.accessorName = HbmHelper.getPropertyAccessorName(
id.getAccess(), isEmbedded(), defaults.getDefaultAccess()
);
this.nodeName = MappingHelper.getStringValue( id.getNode(), attribute.getName() );
this.metaAttributes = HbmHelper.extractMetas( id.getMeta(), entityMetaAttributes );
this.cascade = defaults.getDefaultCascade();
this.isOptimisticLockable = true;
}
public AbstractHbmAttributeDomainState(MappingDefaults defaults,
Attribute attribute,
org.hibernate.metamodel.source.hbm.xml.mapping.Discriminator discriminator) {
this.defaults = defaults;
this.attribute = attribute;
this.hibernateTypeDescriptor = new HibernateTypeDescriptor();
this.hibernateTypeDescriptor.setTypeName( discriminator.getType() == null ? "string" : discriminator.getType() );
// the following does not apply to discriminators
this.accessorName = null;
this.nodeName = null;
this.metaAttributes = null;
this.cascade = null;
this.isOptimisticLockable = true;
}
public AbstractHbmAttributeDomainState(MappingDefaults defaults,
Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Version version) {
this.defaults = defaults;
this.attribute = attribute;
this.hibernateTypeDescriptor = new HibernateTypeDescriptor();
this.hibernateTypeDescriptor.setTypeName( version.getType() == null ? "integer" : version.getType() );
// the following does not apply to discriminators
this.accessorName = HbmHelper.getPropertyAccessorName(
version.getAccess(), isEmbedded(), defaults.getDefaultAccess()
);
this.nodeName = version.getNode();
this.metaAttributes = HbmHelper.extractMetas( version.getMeta(), entityMetaAttributes );
this.cascade = null;
this.isOptimisticLockable = true;
}
public AbstractHbmAttributeDomainState(MappingDefaults defaults,
Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Timestamp timestamp) {
this.defaults = defaults;
this.attribute = attribute;
this.hibernateTypeDescriptor = new HibernateTypeDescriptor();
// Timestamp.getType() is not defined
this.hibernateTypeDescriptor.setTypeName( "db".equals( timestamp.getSource() ) ? "dbtimestamp" : "timestamp" );
// the following does not apply to discriminators
this.accessorName = HbmHelper.getPropertyAccessorName(
timestamp.getAccess(), isEmbedded(), defaults.getDefaultAccess()
);
this.nodeName = timestamp.getNode();
this.metaAttributes = HbmHelper.extractMetas( timestamp.getMeta(), entityMetaAttributes );
this.cascade = null;
this.isOptimisticLockable = true;
}
public AbstractHbmAttributeDomainState(MappingDefaults defaults,
Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Property property) {
this.defaults = defaults;
this.attribute = attribute;
this.hibernateTypeDescriptor = new HibernateTypeDescriptor();
this.hibernateTypeDescriptor.setTypeName( property.getType() );
this.accessorName = HbmHelper.getPropertyAccessorName(
property.getAccess(), isEmbedded(), defaults.getDefaultAccess()
);
this.nodeName = MappingHelper.getStringValue( property.getNode(), attribute.getName() );
this.metaAttributes = HbmHelper.extractMetas( property.getMeta(), entityMetaAttributes );
this.cascade = defaults.getDefaultCascade();
this.isOptimisticLockable = MappingHelper.getBooleanValue( property.getOptimisticLock(), true );
}
public AbstractHbmAttributeDomainState(MappingDefaults defaults,
Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Bag collection) {
this.defaults = defaults;
this.attribute = attribute;
this.hibernateTypeDescriptor = new HibernateTypeDescriptor();
// TODO: is collection.getCollectionType() correct here?
this.hibernateTypeDescriptor.setTypeName( collection.getCollectionType() );
this.accessorName = HbmHelper.getPropertyAccessorName(
collection.getAccess(), isEmbedded(), defaults.getDefaultAccess()
);
this.nodeName = MappingHelper.getStringValue( collection.getNode(), attribute.getName() );
this.metaAttributes = HbmHelper.extractMetas( collection.getMeta(), entityMetaAttributes );
this.cascade = defaults.getDefaultCascade();
this.isOptimisticLockable = MappingHelper.getBooleanValue( collection.getOptimisticLock(), true );
} }
protected final MappingDefaults getDefaults() { protected final MappingDefaults getDefaults() {
return defaults; return defaults;
} }
protected final Element getElement() {
return element;
}
public final HibernateTypeDescriptor getHibernateTypeDescriptor() {
HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
hibernateTypeDescriptor.setTypeName( DomHelper.extractAttributeValue( element, "type", null ) );
return hibernateTypeDescriptor;
}
public final Attribute getAttribute() { public final Attribute getAttribute() {
return attribute; return attribute;
} }
public final HibernateTypeDescriptor getHibernateTypeDescriptor() {
return hibernateTypeDescriptor;
}
public final String getPropertyAccessorName() { public final String getPropertyAccessorName() {
return HbmHelper.getPropertyAccessorName( element, isEmbedded(), defaults.getDefaultAccess() ); return accessorName;
} }
protected abstract boolean isEmbedded(); protected abstract boolean isEmbedded();
@ -77,17 +176,16 @@ public final boolean isAlternateUniqueKey() {
return false; return false;
} }
public final String getCascade() { public final String getCascade() {
return DomHelper.extractAttributeValue( element, "cascade", defaults.getDefaultCascade() ); return cascade;
} }
public final boolean isOptimisticLockable() { public final boolean isOptimisticLockable() {
return DomHelper.extractBooleanAttributeValue( element, "optimistic-lock", true ); return isOptimisticLockable;
} }
public final String getNodeName() { public final String getNodeName() {
return DomHelper.extractAttributeValue( element, "node", attribute.getName() ); return nodeName;
} }
public final Map<String, MetaAttribute> getMetaAttributes(EntityBinding entityBinding) { public final Map<String, MetaAttribute> getMetaAttributes(EntityBinding entityBinding) {
//TODO: implement return metaAttributes;
return HbmHelper.extractMetas( element, entityBinding.getMetaAttributes() );
} }
} }

View File

@ -1,32 +1,48 @@
/*
* 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.domain; package org.hibernate.metamodel.source.hbm.state.domain;
import org.dom4j.Element;
import org.hibernate.metamodel.binding.CollectionElement; import org.hibernate.metamodel.binding.CollectionElement;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor; import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.metamodel.source.util.DomHelper;
/** /**
* Created by IntelliJ IDEA. * @author Gail Badner
* User: gbadner
* Date: 3/29/11
* Time: 9:19 PM
* To change this template use File | Settings | File Templates.
*/ */
public class HbmCollectionElementDomainState implements CollectionElement.DomainState { public class HbmCollectionElementDomainState implements CollectionElement.DomainState {
private final Element element; private final org.hibernate.metamodel.source.hbm.xml.mapping.Element element;
HbmCollectionElementDomainState(Element element) { HbmCollectionElementDomainState(org.hibernate.metamodel.source.hbm.xml.mapping.Element element) {
this.element = element; this.element = element;
} }
public final HibernateTypeDescriptor getHibernateTypeDescriptor() { public final HibernateTypeDescriptor getHibernateTypeDescriptor() {
HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor(); HibernateTypeDescriptor hibernateTypeDescriptor = new HibernateTypeDescriptor();
hibernateTypeDescriptor.setTypeName( DomHelper.extractAttributeValue( element, "type", null ) ); hibernateTypeDescriptor.setTypeName( element.getType() );
return hibernateTypeDescriptor; return hibernateTypeDescriptor;
} }
public final String getNodeName() { public final String getNodeName() {
return DomHelper.extractAttributeValue( element, "node", null ); return element.getNode();
} }
} }

View File

@ -27,6 +27,7 @@
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import org.dom4j.Element; import org.dom4j.Element;
@ -38,28 +39,32 @@
import org.hibernate.metamodel.binding.MappingDefaults; import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.binding.PluralAttributeBinding; import org.hibernate.metamodel.binding.PluralAttributeBinding;
import org.hibernate.metamodel.domain.Attribute; import org.hibernate.metamodel.domain.Attribute;
import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.hbm.HbmHelper; import org.hibernate.metamodel.source.hbm.HbmHelper;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainState implements PluralAttributeBinding.DomainState { public class HbmPluralAttributeDomainState extends AbstractHbmAttributeDomainState implements PluralAttributeBinding.DomainState {
private final org.hibernate.metamodel.source.hbm.xml.mapping.Bag collection;
public HbmPluralAttributeDomainState(MappingDefaults defaults, public HbmPluralAttributeDomainState(MappingDefaults defaults,
Element element, org.hibernate.metamodel.source.hbm.xml.mapping.Bag collection,
Map<String, MetaAttribute> entityMetaAttributes,
Attribute attribute) { Attribute attribute) {
super( defaults, element, attribute ); super( defaults, attribute, entityMetaAttributes, collection );
this.collection = collection;
} }
public FetchMode getFetchMode() { public FetchMode getFetchMode() {
FetchMode fetchMode; FetchMode fetchMode;
org.dom4j.Attribute fetchModeAttribute = getElement().attribute( "fetch" ); if ( collection.getFetch() != null ) {
if ( fetchModeAttribute != null ) { fetchMode = "join".equals( collection.getFetch() ) ? FetchMode.JOIN : FetchMode.SELECT;
fetchMode = "join".equals( fetchModeAttribute.getValue() ) ? FetchMode.JOIN : FetchMode.SELECT;
} }
else { else {
org.dom4j.Attribute jfNode = getElement().attribute( "outer-join" ); String jfNodeValue = ( collection.getOuterJoin() == null ? "auto" : collection.getOuterJoin() );
String jfNodeValue = ( jfNode == null ? "auto" : jfNode.getValue() );
if ( "auto".equals( jfNodeValue ) ) { if ( "auto".equals( jfNodeValue ) ) {
fetchMode = FetchMode.DEFAULT; fetchMode = FetchMode.DEFAULT;
} }
@ -75,48 +80,48 @@ else if ( "true".equals( jfNodeValue ) ) {
public boolean isLazy() { public boolean isLazy() {
return isExtraLazy() || return isExtraLazy() ||
DomHelper.extractBooleanAttributeValue( getElement(), "lazy", getDefaults().isDefaultLazy() ); MappingHelper.getBooleanValue( collection.getLazy(), getDefaults().isDefaultLazy());
} }
public boolean isExtraLazy() { public boolean isExtraLazy() {
String lazyString = DomHelper.extractAttributeValue( getElement(), "lazy" ); return ( "extra".equals( collection.getLazy() ) );
return ( "extra".equals( lazyString ) );
} }
public CollectionElement getCollectionElement(PluralAttributeBinding binding) { public CollectionElement getCollectionElement(PluralAttributeBinding binding) {
Element element = getElement().element( "element" );
if ( element != null ) {
ElementCollectionElement collectionElement = new ElementCollectionElement( binding ); ElementCollectionElement collectionElement = new ElementCollectionElement( binding );
collectionElement.initialize( new HbmCollectionElementDomainState( element ) ); collectionElement.initialize( new HbmCollectionElementDomainState( collection.getElement() ) );
} return collectionElement;
// TODO: implement other types of collection elements
return null;
} }
public boolean isInverse() { public boolean isInverse() {
return DomHelper.extractBooleanAttributeValue( getElement(), "inverse", false ); return MappingHelper.getBooleanValue( collection.getInverse(), false );
} }
public boolean isMutable() { public boolean isMutable() {
return DomHelper.extractBooleanAttributeValue( getElement(), "mutable", true ); return MappingHelper.getBooleanValue( collection.getMutable(), true );
} }
public boolean isSubselectLoadable() { public boolean isSubselectLoadable() {
return "subselect".equals( getElement().attributeValue( "fetch" ) ); return "subselect".equals( collection.getFetch() );
} }
public String getCacheConcurrencyStrategy() { public String getCacheConcurrencyStrategy() {
Element cacheElement = getElement().element( "cache" ); return collection.getCache() == null ?
return cacheElement == null ? null : cacheElement.attributeValue( "usage" ); null :
collection.getCache().getUsage();
} }
public String getCacheRegionName() { public String getCacheRegionName() {
Element cacheElement = getElement().element( "cache" ); return collection.getCache() == null ?
return cacheElement == null ? null : cacheElement.attributeValue( "region" ); null :
collection.getCache().getRegion();
} }
public String getOrderBy() { public String getOrderBy() {
return DomHelper.extractAttributeValue( getElement(), "order-by", null ); return collection.getOrderBy();
} }
public String getWhere() { public String getWhere() {
return DomHelper.extractAttributeValue( getElement(), "where", null ); return collection.getWhere();
} }
public String getReferencedPropertyName() { public String getReferencedPropertyName() {
return getElement().element( "key" ).attributeValue( "property-ref" ); return collection.getKey().getPropertyRef();
} }
public boolean isSorted() { public boolean isSorted() {
// SORT // SORT
@ -137,29 +142,31 @@ public String getComparatorClassName() {
} }
private String getSortString() { private String getSortString() {
return DomHelper.extractAttributeValue( getElement(), "sort", "unsorted" ); //TODO: Bag does not define getSort(); update this when there is a Collection subtype
// collection.getSort() == null ? "unsorted" : collection.getSort();
return "unsorted";
} }
public boolean isOrphanDelete() { public boolean isOrphanDelete() {
// ORPHAN DELETE (used for programmer error detection) // ORPHAN DELETE (used for programmer error detection)
return ( getCascade().indexOf( "delete-orphan" ) >= 0 ); return ( getCascade().indexOf( "delete-orphan" ) >= 0 );
} }
public int getBatchSize() { public int getBatchSize() {
return DomHelper.extractIntAttributeValue( getElement(), "batch-size", 0 ); return MappingHelper.getIntValue( collection.getBatchSize(), 0 );
} }
public boolean isEmbedded() { public boolean isEmbedded() {
return DomHelper.extractBooleanAttributeValue( getElement(), "embed-xml", true ); return MappingHelper.getBooleanValue( collection.getEmbedXml(), true );
} }
public boolean isOptimisticLocked() { public boolean isOptimisticLocked() {
return true; return MappingHelper.getBooleanValue( collection.getOptimisticLock(), true );
} }
public Class getCollectionPersisterClass() { public Class getCollectionPersisterClass() {
try { try {
return DomHelper.extractClassAttributeValue( getElement(), "persister" ); return MappingHelper.getClassValue( collection.getPersister() );
} }
catch (ClassNotFoundException cnfe) { catch (ClassNotFoundException cnfe) {
throw new MappingException( "Could not find collection persister class: " throw new MappingException( "Could not find collection persister class: "
+ getElement().attributeValue( "persister" ) ); + collection.getPersister() );
} }
} }
public String getTypeName() { public String getTypeName() {
@ -193,28 +200,56 @@ public java.util.Map getFilters() {
} }
public java.util.Set getSynchronizedTables() { public java.util.Set getSynchronizedTables() {
java.util.Set<String> synchronizedTables = new HashSet<String>(); java.util.Set<String> synchronizedTables = new HashSet<String>();
Iterator tables = getElement().elementIterator( "synchronize" ); for ( org.hibernate.metamodel.source.hbm.xml.mapping.Synchronize sync : collection.getSynchronize() ) {
while ( tables.hasNext() ) { synchronizedTables.add( sync.getTable() );
synchronizedTables.add( ( ( Element ) tables.next() ).attributeValue( "table" ) );
} }
return synchronizedTables; return synchronizedTables;
} }
public CustomSQL getCustomSQLInsert() { public CustomSQL getCustomSQLInsert() {
return HbmHelper.getCustomSql( getElement().element( "sql-insert" ) ); org.hibernate.metamodel.source.hbm.xml.mapping.SqlInsert sqlInsert = collection.getSqlInsert();
return sqlInsert == null ?
null :
HbmHelper.getCustomSql(
collection.getSqlInsert().getContent(),
MappingHelper.getBooleanValue( collection.getSqlInsert().getCallable(), false ),
collection.getSqlInsert().getCheck()
);
} }
public CustomSQL getCustomSQLUpdate() { public CustomSQL getCustomSQLUpdate() {
return HbmHelper.getCustomSql( getElement().element( "sql-update" ) ); org.hibernate.metamodel.source.hbm.xml.mapping.SqlUpdate sqlUpdate = collection.getSqlUpdate();
return sqlUpdate == null ?
null :
HbmHelper.getCustomSql(
collection.getSqlUpdate().getContent(),
MappingHelper.getBooleanValue( collection.getSqlUpdate().getCallable(), false ),
collection.getSqlUpdate().getCheck()
);
} }
public CustomSQL getCustomSQLDelete() { public CustomSQL getCustomSQLDelete() {
return HbmHelper.getCustomSql( getElement().element( "sql-delete" ) ); org.hibernate.metamodel.source.hbm.xml.mapping.SqlDelete sqlDelete = collection.getSqlDelete();
return sqlDelete == null ?
null :
HbmHelper.getCustomSql(
collection.getSqlDelete().getContent(),
MappingHelper.getBooleanValue( collection.getSqlDelete().getCallable(), false ),
collection.getSqlDelete().getCheck()
);
} }
public CustomSQL getCustomSQLDeleteAll() { public CustomSQL getCustomSQLDeleteAll() {
return HbmHelper.getCustomSql( getElement().element( "sql-delete-all" ) ); org.hibernate.metamodel.source.hbm.xml.mapping.SqlDeleteAll sqlDeleteAll = collection.getSqlDeleteAll();
return sqlDeleteAll == null ?
null :
HbmHelper.getCustomSql(
collection.getSqlDeleteAll().getContent(),
MappingHelper.getBooleanValue( collection.getSqlDeleteAll().getCallable(), false ),
collection.getSqlDeleteAll().getCheck()
);
} }
public String getLoaderName() { public String getLoaderName() {
return DomHelper.extractAttributeValue( getElement().element( "loader" ), "query-ref" ); return collection.getLoader() == null ?
null :
collection.getLoader().getQueryRef();
} }
public boolean isKeyCasadeDeleteEnabled() { public boolean isKeyCasadeDeleteEnabled() {

View File

@ -23,22 +23,127 @@
*/ */
package org.hibernate.metamodel.source.hbm.state.domain; package org.hibernate.metamodel.source.hbm.state.domain;
import org.dom4j.Element; import java.util.Map;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.mapping.PropertyGeneration; import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.binding.MappingDefaults; import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.binding.SimpleAttributeBinding; import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.domain.MetaAttribute;
import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainState implements SimpleAttributeBinding.DomainState { public class HbmSimpleAttributeDomainState extends AbstractHbmAttributeDomainState implements SimpleAttributeBinding.DomainState {
private final boolean isLazy;
private final PropertyGeneration propertyGeneration;
private final boolean isInsertable;
private final boolean isUpdateable;
public HbmSimpleAttributeDomainState(MappingDefaults defaults, public HbmSimpleAttributeDomainState(MappingDefaults defaults,
final Element element, org.hibernate.metamodel.domain.Attribute attribute,
org.hibernate.metamodel.domain.Attribute attribute) { Map<String, MetaAttribute> entityMetaAttributes,
super( defaults, element, attribute ); org.hibernate.metamodel.source.hbm.xml.mapping.Id id) {
super( defaults, attribute, entityMetaAttributes, id );
this.isLazy = false;
// TODO: how should these be set???
this.propertyGeneration = PropertyGeneration.parse( null );
this.isInsertable = true;
this.isUpdateable = false;
}
public HbmSimpleAttributeDomainState(MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Discriminator discriminator) {
super( defaults, attribute, discriminator );
this.isLazy = false;
this.propertyGeneration = PropertyGeneration.NEVER;
this.isInsertable = MappingHelper.getBooleanValue( discriminator.getInsert(), true );
this.isUpdateable = false;
}
public HbmSimpleAttributeDomainState(MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Version version) {
super( defaults, attribute, entityMetaAttributes, version );
this.isLazy = false;
// for version properties marked as being generated, make sure they are "always"
// generated; aka, "insert" is invalid; this is dis-allowed by the DTD,
// but just to make sure.
this.propertyGeneration = PropertyGeneration.parse( version.getGenerated() );
if ( propertyGeneration == PropertyGeneration.INSERT ) {
throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
}
this.isInsertable = MappingHelper.getBooleanValue( version.getInsert(), true );
this.isUpdateable = true;
}
public HbmSimpleAttributeDomainState(MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Timestamp timestamp) {
super( defaults, attribute, entityMetaAttributes, timestamp );
this.isLazy = false;
// for version properties marked as being generated, make sure they are "always"
// generated; aka, "insert" is invalid; this is dis-allowed by the DTD,
// but just to make sure.
this.propertyGeneration = PropertyGeneration.parse( timestamp.getGenerated() );
if ( propertyGeneration == PropertyGeneration.INSERT ) {
throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
}
this.isInsertable = true; //TODO: is this right????
this.isUpdateable = true;
}
public HbmSimpleAttributeDomainState(MappingDefaults defaults,
org.hibernate.metamodel.domain.Attribute attribute,
Map<String, MetaAttribute> entityMetaAttributes,
org.hibernate.metamodel.source.hbm.xml.mapping.Property property) {
super( defaults, attribute, entityMetaAttributes, property );
this.isLazy = MappingHelper.getBooleanValue( property.getLazy(), false );
;
this.propertyGeneration = PropertyGeneration.parse( property.getGenerated() );
if ( propertyGeneration == PropertyGeneration.ALWAYS || propertyGeneration == PropertyGeneration.INSERT ) {
// generated properties can *never* be insertable.
if ( property.getInsert() != null && Boolean.parseBoolean( property.getInsert() ) ) {
// the user specifically supplied insert="true", which constitutes an illegal combo
throw new MappingException(
"cannot specify both insert=\"true\" and generated=\"" + propertyGeneration.getName() +
"\" for property: " +
getAttribute().getName()
);
}
isInsertable = false;
}
else {
isInsertable = MappingHelper.getBooleanValue( property.getInsert(), true );
}
if ( propertyGeneration == PropertyGeneration.ALWAYS ) {
if ( property.getUpdate() != null && Boolean.parseBoolean( property.getUpdate() ) ) {
// the user specifically supplied update="true",
// which constitutes an illegal combo
throw new MappingException(
"cannot specify both update=\"true\" and generated=\"" + propertyGeneration.getName() +
"\" for property: " +
getAttribute().getName()
);
}
isUpdateable = false;
}
else {
isUpdateable = MappingHelper.getBooleanValue( property.getUpdate(), true );
}
} }
protected boolean isEmbedded() { protected boolean isEmbedded() {
@ -46,56 +151,16 @@ protected boolean isEmbedded() {
} }
public boolean isLazy() { public boolean isLazy() {
return DomHelper.extractBooleanAttributeValue( getElement(), "lazy", false ); return isLazy;
} }
public PropertyGeneration getPropertyGeneration() { public PropertyGeneration getPropertyGeneration() {
return PropertyGeneration.parse( DomHelper.extractAttributeValue( getElement(), "generated", null ) ); return propertyGeneration;
} }
public boolean isInsertable() { public boolean isInsertable() {
//TODO: implement
PropertyGeneration generation = getPropertyGeneration();
boolean isInsertable = DomHelper.extractBooleanAttributeValue( getElement(), "insert", true );
if ( generation == PropertyGeneration.ALWAYS || generation == PropertyGeneration.INSERT ) {
// generated properties can *never* be insertable...
if ( isInsertable ) {
final org.dom4j.Attribute insertAttribute = getElement().attribute( "insert" );
if ( insertAttribute == null ) {
// insertable simply because the user did not specify anything; just override it
isInsertable = false;
}
else {
// the user specifically supplied insert="true", which constitutes an illegal combo
throw new MappingException(
"cannot specify both insert=\"true\" and generated=\"" + generation.getName() +
"\" for property: " +
getAttribute().getName()
);
}
}
}
return isInsertable; return isInsertable;
} }
public boolean isUpdateable() { public boolean isUpdateable() {
PropertyGeneration generation = getPropertyGeneration();
boolean isUpdateable = DomHelper.extractBooleanAttributeValue( getElement(), "update", true );
if ( isUpdateable && generation == PropertyGeneration.ALWAYS ) {
final org.dom4j.Attribute updateAttribute = getElement().attribute( "update" );
if ( updateAttribute == null ) {
// updateable only because the user did not specify
// anything; just override it
isUpdateable = false;
}
else {
// the user specifically supplied update="true",
// which constitutes an illegal combo
throw new MappingException(
"cannot specify both update=\"true\" and generated=\"" + generation.getName() +
"\" for property: " +
getAttribute().getName()
);
}
}
return isUpdateable; return isUpdateable;
} }
public boolean isKeyCasadeDeleteEnabled() { public boolean isKeyCasadeDeleteEnabled() {

View File

@ -25,92 +25,215 @@
import java.util.Set; import java.util.Set;
import org.dom4j.Element;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.binding.SimpleAttributeBinding; import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.relational.Size; import org.hibernate.metamodel.relational.Size;
import org.hibernate.metamodel.source.util.DomHelper; import org.hibernate.metamodel.source.util.MappingHelper;
// TODO: remove duplication after Id, Discriminator, Version, Timestamp, and Property extend a common interface.
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class HbmColumnRelationalState extends HbmRelationalState implements SimpleAttributeBinding.ColumnRelationalState { public class HbmColumnRelationalState implements SimpleAttributeBinding.ColumnRelationalState {
private final HbmSimpleValueRelationalStateContainer container; private final HbmSimpleValueRelationalStateContainer container;
private final String explicitColumnName;
private final Size size;
private final boolean isNullable;
private final boolean isUnique;
private final String checkCondition;
private final String defaultColumnValue;
private final String sqlType;
private final String customWrite;
private final String customRead;
private final String comment;
private final Set<String> uniqueKeys;
private final Set<String> indexes;
/* package-protected */ /* package-protected */
HbmColumnRelationalState(Element columnElement, HbmColumnRelationalState(org.hibernate.metamodel.source.hbm.xml.mapping.ColumnElement columnElement,
HbmSimpleValueRelationalStateContainer container) { HbmSimpleValueRelationalStateContainer container) {
super( columnElement );
this.container = container; this.container = container;
this.explicitColumnName = columnElement.getName();
this.size = createSize( columnElement.getLength(), columnElement.getScale(), columnElement.getPrecision() );
this.isNullable = createNullable( columnElement.getNotNull() );
this.isUnique = createUnique( columnElement.getUnique() );
this.checkCondition = columnElement.getCheck();
this.defaultColumnValue = columnElement.getDefault();
this.sqlType = columnElement.getSqlType();
this.customWrite = columnElement.getWrite();
if ( customWrite != null && ! customWrite.matches("[^?]*\\?[^?]*") ) {
throw new MappingException("write expression must contain exactly one value placeholder ('?') character");
}
this.customRead = columnElement.getRead();
this.comment = columnElement.getComment() == null ? null : columnElement.getComment().trim();
this.uniqueKeys = MappingHelper.getStringValueTokens( columnElement.getUniqueKey(), ", " );
this.uniqueKeys.addAll( container.getPropertyUniqueKeys() );
this.indexes = MappingHelper.getStringValueTokens( columnElement.getIndex(), ", " );
this.indexes.addAll( container.getPropertyIndexes() );
}
HbmColumnRelationalState(org.hibernate.metamodel.source.hbm.xml.mapping.Property property,
HbmSimpleValueRelationalStateContainer container) {
this.container = container;
this.explicitColumnName = property.getName();
this.size = createSize( property.getLength(), property.getScale(), property.getPrecision() );
this.isNullable = createNullable( property.getNotNull() );
this.isUnique = createUnique( property.getUnique() );
this.checkCondition = null;
this.defaultColumnValue = null;
this.sqlType = null;
this.customWrite = null;
this.customRead = null;
this.comment = null;
this.uniqueKeys = MappingHelper.getStringValueTokens( property.getUniqueKey(), ", " );
this.uniqueKeys.addAll( container.getPropertyUniqueKeys() );
this.indexes = MappingHelper.getStringValueTokens( property.getIndex(), ", " );
this.indexes.addAll( container.getPropertyIndexes() );
}
HbmColumnRelationalState(org.hibernate.metamodel.source.hbm.xml.mapping.Id id,
HbmSimpleValueRelationalStateContainer container) {
if ( id.getColumnElement() != null && ! id.getColumnElement().isEmpty() ) {
throw new IllegalArgumentException( "This method should not be called with non-empty id.getColumnElement()" );
}
this.container = container;
this.explicitColumnName = id.getName();
this.size = createSize( id.getLength(), null, null );
this.isNullable = false;
this.isUnique = true;
this.checkCondition = null;
this.defaultColumnValue = null;
this.sqlType = null;
this.customWrite = null;
this.customRead = null;
this.comment = null;
this.uniqueKeys = container.getPropertyUniqueKeys();
this.indexes = container.getPropertyIndexes();
}
HbmColumnRelationalState(org.hibernate.metamodel.source.hbm.xml.mapping.Discriminator discriminator,
HbmSimpleValueRelationalStateContainer container) {
if ( discriminator.getColumnElement() != null ) {
throw new IllegalArgumentException( "This method should not be called with null discriminator.getColumnElement()" );
}
this.container = container;
this.explicitColumnName = null;
this.size = createSize( discriminator.getLength(), null, null );
this.isNullable = false;
this.isUnique = true;
this.checkCondition = null;
this.defaultColumnValue = null;
this.sqlType = null;
this.customWrite = null;
this.customRead = null;
this.comment = null;
this.uniqueKeys = container.getPropertyUniqueKeys();
this.indexes = container.getPropertyIndexes();
}
HbmColumnRelationalState(org.hibernate.metamodel.source.hbm.xml.mapping.Version version,
HbmSimpleValueRelationalStateContainer container) {
this.container = container;
this.explicitColumnName = version.getColumn();
if ( version.getColumnElement() != null && ! version.getColumnElement().isEmpty() ) {
throw new IllegalArgumentException( "This method should not be called with non-empty version.getColumnElement()" );
}
// TODO: should set default
this.size = new Size();
this.isNullable = false;
this.isUnique = false;
this.checkCondition = null;
this.defaultColumnValue = null;
this.sqlType = null; // TODO: figure out the correct setting
this.customWrite = null;
this.customRead = null;
this.comment = null;
this.uniqueKeys = container.getPropertyUniqueKeys();
this.indexes = container.getPropertyIndexes();
}
HbmColumnRelationalState(org.hibernate.metamodel.source.hbm.xml.mapping.Timestamp timestamp,
HbmSimpleValueRelationalStateContainer container) {
this.container = container;
this.explicitColumnName = timestamp.getColumn();
// TODO: should set default
this.size = new Size();
this.isNullable = false;
this.isUnique = true; // well, it should hopefully be unique...
this.checkCondition = null;
this.defaultColumnValue = null;
this.sqlType = null; // TODO: figure out the correct setting
this.customWrite = null;
this.customRead = null;
this.comment = null;
this.uniqueKeys = container.getPropertyUniqueKeys();
this.indexes = container.getPropertyIndexes();
} }
public NamingStrategy getNamingStrategy() { public NamingStrategy getNamingStrategy() {
return container.getNamingStrategy(); return container.getNamingStrategy();
} }
public String getExplicitColumnName() { public String getExplicitColumnName() {
return getElement().attributeValue( "name" ); return explicitColumnName;
} }
public Size getSize() { public Size getSize() {
return size;
}
private static Size createSize(String length, String scale, String precision) {
// TODO: should this set defaults if length, scale, precision is not specified? // TODO: should this set defaults if length, scale, precision is not specified?
Size size = new Size(); Size size = new Size();
org.dom4j.Attribute lengthNode = getElement().attribute( "length" ); if ( length != null ) {
if ( lengthNode != null ) { size.setLength( Integer.parseInt( length ) );
size.setLength( Integer.parseInt( lengthNode.getValue() ) );
} }
org.dom4j.Attribute scaleNode = getElement().attribute( "scale" ); if ( scale != null ) {
if ( scaleNode != null ) { size.setScale( Integer.parseInt( scale ) );
size.setScale( Integer.parseInt( scaleNode.getValue() ) );
} }
org.dom4j.Attribute precisionNode = getElement().attribute( "precision" ); if ( precision != null ) {
if ( precisionNode != null ) { size.setPrecision( Integer.parseInt( precision ) );
size.setPrecision( Integer.parseInt( precisionNode.getValue() ) );
} }
// TODO: is there an attribute for lobMultiplier? // TODO: is there an attribute for lobMultiplier?
return size; return size;
} }
public boolean isNullable() { public boolean isNullable() {
return ! DomHelper.extractBooleanAttributeValue( getElement(), "not-null", false ); return isNullable;
}
private static boolean createNullable(String notNullString ) {
return ! MappingHelper.getBooleanValue( notNullString, false );
} }
public boolean isUnique() { public boolean isUnique() {
return ! DomHelper.extractBooleanAttributeValue( getElement(), "unique", false ); return isUnique;
}
private boolean createUnique(String uniqueString) {
return ! MappingHelper.getBooleanValue( uniqueString, false );
} }
public String getCheckCondition() { public String getCheckCondition() {
return getElement().attributeValue( "check" ); return checkCondition;
} }
public String getDefault() { public String getDefault() {
return getElement().attributeValue( "default" ); return defaultColumnValue;
} }
public String getSqlType() { public String getSqlType() {
return getElement().attributeValue( "sql-type" ); return sqlType;
} }
public String getCustomWriteFragment() { public String getCustomWriteFragment() {
String customWrite = getElement().attributeValue( "write" );
if ( customWrite != null && ! customWrite.matches("[^?]*\\?[^?]*") ) {
throw new MappingException("write expression must contain exactly one value placeholder ('?') character");
}
return customWrite; return customWrite;
} }
public String getCustomReadFragment() { public String getCustomReadFragment() {
return getElement().attributeValue( "read" ); return customRead;
} }
public String getComment() { public String getComment() {
Element comment = getElement().element( "comment" ); return comment;
return comment == null ?
null :
comment.getTextTrim();
} }
public Set<String> getUniqueKeys() { public Set<String> getUniqueKeys() {
Set<String> uniqueKeys = DomHelper.extractUniqueAttributeValueTokens( getElement(), "unique-key", ", " );
uniqueKeys.addAll( container.getPropertyUniqueKeys() );
return uniqueKeys; return uniqueKeys;
} }
public Set<String> getIndexes() { public Set<String> getIndexes() {
Set<String> indexes = DomHelper.extractUniqueAttributeValueTokens( getElement(), "index", ", " );
indexes.addAll( container.getPropertyIndexes() );
return indexes; return indexes;
} }
} }

View File

@ -30,13 +30,14 @@
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class HbmDerivedValueRelationalState extends HbmRelationalState implements SimpleAttributeBinding.DerivedRelationalState { public class HbmDerivedValueRelationalState implements SimpleAttributeBinding.DerivedRelationalState {
private final String formula;
public HbmDerivedValueRelationalState(Element element, HbmSimpleValueRelationalStateContainer container) { public HbmDerivedValueRelationalState(String formula) {
super( element ); this.formula = formula.trim();
} }
public String getFormula() { public String getFormula() {
return getElement().getTextTrim(); return formula;
} }
} }

View File

@ -23,69 +23,150 @@
*/ */
package org.hibernate.metamodel.source.hbm.state.relational; package org.hibernate.metamodel.source.hbm.state.relational;
import java.util.Iterator; import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.metamodel.binding.MappingDefaults; import org.hibernate.metamodel.binding.MappingDefaults;
import org.hibernate.metamodel.binding.SimpleAttributeBinding; import org.hibernate.metamodel.binding.SimpleAttributeBinding;
import org.hibernate.metamodel.source.util.DomHelper;
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class HbmSimpleValueRelationalStateContainer extends HbmRelationalState implements SimpleAttributeBinding.TupleRelationalState { public class HbmSimpleValueRelationalStateContainer implements SimpleAttributeBinding.TupleRelationalState {
private final MappingDefaults defaults; private final MappingDefaults defaults;
private final Set<String> propertyUniqueKeys; private final Set<String> propertyUniqueKeys;
private final Set<String> propertyIndexes; private final Set<String> propertyIndexes;
private final LinkedHashSet<SimpleAttributeBinding.SingleValueRelationalState> singleValueStates = private final Set<SimpleAttributeBinding.SingleValueRelationalState> singleValueStates;
new LinkedHashSet<SimpleAttributeBinding.SingleValueRelationalState>();
public NamingStrategy getNamingStrategy() { public NamingStrategy getNamingStrategy() {
return defaults.getNamingStrategy(); return defaults.getNamingStrategy();
} }
// TODO: remove duplication after Id, Discriminator, Version, Timestamp, and Property extend a common interface.
public HbmSimpleValueRelationalStateContainer(MappingDefaults defaults, public HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
Element propertyElement, boolean autoColumnCreation,
boolean autoColumnCreation) { org.hibernate.metamodel.source.hbm.xml.mapping.Id id) {
super( propertyElement ); this( defaults, id.getColumnElement() );
this.defaults = defaults; if ( singleValueStates.isEmpty() ) {
this.propertyUniqueKeys = DomHelper.extractUniqueAttributeValueTokens( propertyElement, "unique-key", ", " ); if ( id.getColumn() == null && ! autoColumnCreation ) {
this.propertyIndexes = DomHelper.extractUniqueAttributeValueTokens( propertyElement, "index", ", " ); throw new MappingException( "No columns to map and auto column creation is disabled." );
final Attribute columnAttribute = getElement().attribute( "column" );
if ( columnAttribute == null ) {
final Iterator valueElements = getElement().elementIterator();
while ( valueElements.hasNext() ) {
final Element valueElement = (Element) valueElements.next();
if ( "column".equals( valueElement.getName() ) ) {
singleValueStates.add( new HbmColumnRelationalState( valueElement, this ) );
} }
else if ( "formula".equals( valueElement.getName() ) ) { singleValueStates.add( new HbmColumnRelationalState( id, this ) );
singleValueStates.add( new HbmDerivedValueRelationalState( valueElement, this ) );
} }
} else if ( id.getColumn() != null ) {
}
else {
if ( propertyElement.elementIterator( "column" ).hasNext() ) {
throw new MappingException( "column attribute may not be used together with <column> subelement" ); throw new MappingException( "column attribute may not be used together with <column> subelement" );
} }
if ( propertyElement.elementIterator( "formula" ).hasNext() ) {
throw new MappingException( "column attribute may not be used together with <formula> subelement" );
}
singleValueStates.add( new HbmColumnRelationalState( propertyElement, this ) );
}
// TODO: should it actually check for 0 columns???
if ( singleValueStates.isEmpty() && autoColumnCreation ) {
singleValueStates.add( new HbmColumnRelationalState( propertyElement, this ) );
}
} }
public LinkedHashSet<SimpleAttributeBinding.SingleValueRelationalState> getSingleValueRelationalStates() { public HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
boolean autoColumnCreation,
org.hibernate.metamodel.source.hbm.xml.mapping.Discriminator discriminator) {
this( defaults, discriminator.getFormulaElement(), discriminator.getColumnElement() );
if ( singleValueStates.isEmpty() ) {
if ( discriminator.getColumn() == null && discriminator.getFormula() == null && ! autoColumnCreation ) {
throw new MappingException( "No column or formula to map and auto column creation is disabled." );
}
singleValueStates.add( new HbmColumnRelationalState( discriminator, this ) );
}
else if ( discriminator.getColumn() != null || discriminator.getFormula() != null) {
throw new MappingException( "column/formula attribute may not be used together with <column>/<formula> subelement" );
}
}
public HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
boolean autoColumnCreation,
org.hibernate.metamodel.source.hbm.xml.mapping.Version version) {
this( defaults, version.getColumnElement() );
if ( singleValueStates.isEmpty() ) {
if ( version.getColumn() == null && ! autoColumnCreation ) {
throw new MappingException( "No column or formula to map and auto column creation is disabled." );
}
singleValueStates.add( new HbmColumnRelationalState( version, this ) );
}
else if ( version.getColumn() != null ) {
throw new MappingException( "column attribute may not be used together with <column> subelement" );
}
}
public HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
boolean autoColumnCreation,
org.hibernate.metamodel.source.hbm.xml.mapping.Timestamp timestamp) {
this( defaults, null );
if ( singleValueStates.isEmpty() ) {
if ( timestamp.getColumn() == null && ! autoColumnCreation ) {
throw new MappingException( "No columns to map and auto column creation is disabled." );
}
singleValueStates.add( new HbmColumnRelationalState( timestamp, this ) );
}
else if ( timestamp.getColumn() != null ) {
throw new MappingException( "column attribute may not be used together with <column> subelement" );
}
}
public HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
boolean autoColumnCreation,
org.hibernate.metamodel.source.hbm.xml.mapping.Property property) {
this( defaults, property.getColumnElementOrFormulaElement() );
if ( singleValueStates.isEmpty() ) {
if ( property.getColumn() == null && property.getFormula() == null && ! autoColumnCreation ) {
throw new MappingException( "No column or formula to map and auto column creation is disabled." );
}
singleValueStates.add( new HbmColumnRelationalState( property, this ) );
}
else if ( property.getColumn() != null || property.getFormula() != null) {
throw new MappingException( "column/formula attribute may not be used together with <column>/<formula> subelement" );
}
}
private HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
String formulaElement,
org.hibernate.metamodel.source.hbm.xml.mapping.ColumnElement columnElement
) {
this( defaults,
formulaElement != null ?
Collections.singletonList( formulaElement ) :
columnElement != null ? Collections.singletonList( columnElement ) : Collections.<Object>emptyList()
);
}
private HbmSimpleValueRelationalStateContainer(MappingDefaults defaults,
List mappedColumnsOrFormulas) {
this.defaults = defaults;
this.propertyUniqueKeys = Collections.emptySet();
this.propertyIndexes = Collections.emptySet();
singleValueStates = new LinkedHashSet<SimpleAttributeBinding.SingleValueRelationalState>(
mappedColumnsOrFormulas == null || mappedColumnsOrFormulas.isEmpty() ?
1 :
mappedColumnsOrFormulas.size()
);
if ( mappedColumnsOrFormulas != null && ! mappedColumnsOrFormulas.isEmpty() ) {
for ( Object mappedColumnOrFormula : mappedColumnsOrFormulas ) {
singleValueStates.add( createColumnOrFormulaRelationalState( this, mappedColumnOrFormula ) );
}
}
}
private static SimpleAttributeBinding.SingleValueRelationalState createColumnOrFormulaRelationalState(
HbmSimpleValueRelationalStateContainer container,
Object columnOrFormula) {
if ( org.hibernate.metamodel.source.hbm.xml.mapping.ColumnElement.class.isInstance( columnOrFormula ) ) {
return new HbmColumnRelationalState(
org.hibernate.metamodel.source.hbm.xml.mapping.ColumnElement.class.cast( columnOrFormula ),
container
);
}
else if ( String.class.isInstance( columnOrFormula ) ) {
return new HbmDerivedValueRelationalState( String.class.cast( columnOrFormula ) );
}
throw new MappingException( "unknown type of column or formula: " + columnOrFormula.getClass().getName() );
}
public Set<SimpleAttributeBinding.SingleValueRelationalState> getSingleValueRelationalStates() {
return singleValueStates; return singleValueStates;
} }

View File

@ -187,6 +187,19 @@ public JaxbRoot unmarshal(Document document, Origin origin) {
return new JaxbRoot( target, origin ); return new JaxbRoot( target, origin );
} }
private Object createTarget(Document document, Origin origin, Schema validationSchema, Class targetClass ) {
final Object target;
try {
JAXBContext jaxbContext = JAXBContext.newInstance( targetClass );
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema( validationSchema );
return unmarshaller.unmarshal( new DOMSource( document ) );
}
catch (JAXBException e) {
throw new MappingException( "Unable to perform unmarshalling", e, origin );
}
}
private Schema resolveSupportedOrmXsd(String explicitVersion) { private Schema resolveSupportedOrmXsd(String explicitVersion) {
final String xsdVersionString = explicitVersion == null ? ASSUMED_ORM_XSD_VERSION : explicitVersion; final String xsdVersionString = explicitVersion == null ? ASSUMED_ORM_XSD_VERSION : explicitVersion;
if ( "1.0".equals( xsdVersionString ) ) { if ( "1.0".equals( xsdVersionString ) ) {

View File

@ -32,9 +32,9 @@
import org.hibernate.DuplicateMappingException; import org.hibernate.DuplicateMappingException;
import org.hibernate.cfg.NamingStrategy; import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.FetchProfile;
import org.hibernate.mapping.MetadataSource; import org.hibernate.mapping.MetadataSource;
import org.hibernate.metamodel.binding.EntityBinding; import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.metamodel.binding.PluralAttributeBinding; import org.hibernate.metamodel.binding.PluralAttributeBinding;
import org.hibernate.metamodel.relational.Database; import org.hibernate.metamodel.relational.Database;
import org.hibernate.metamodel.source.Metadata; import org.hibernate.metamodel.source.Metadata;

View File

@ -44,8 +44,9 @@
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.cfg.MetadataSourceType; import org.hibernate.cfg.MetadataSourceType;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.metamodel.source.hbm.HibernateMappingJaxbRoot;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
import org.hibernate.metamodel.source.util.MappingHelper;
/** /**
* Container for xml configuration documents and annotated classes. * Container for xml configuration documents and annotated classes.
@ -58,9 +59,9 @@ public class MetadataSourceQueue implements Serializable {
); );
private final MetadataImpl metadata; private final MetadataImpl metadata;
private LinkedHashMap<XmlDocument, Set<String>> hbmMetadataToEntityNamesMap private LinkedHashMap<JaxbRoot, Set<String>> hbmMetadataToEntityNamesMap
= new LinkedHashMap<XmlDocument, Set<String>>(); = new LinkedHashMap<JaxbRoot, Set<String>>();
private Map<String, XmlDocument> hbmMetadataByEntityNameXRef = new HashMap<String, XmlDocument>(); private Map<String, JaxbRoot> hbmMetadataByEntityNameXRef = new HashMap<String, JaxbRoot>();
private transient List<Class> annotatedClasses = new ArrayList<Class>(); private transient List<Class> annotatedClasses = new ArrayList<Class>();
public MetadataSourceQueue(MetadataImpl metadata) { public MetadataSourceQueue(MetadataImpl metadata) {
@ -75,6 +76,7 @@ private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); out.defaultWriteObject();
} }
/* TODO: needed anymore???
public void add(XmlDocument metadataXml) { public void add(XmlDocument metadataXml) {
final Document document = metadataXml.getDocumentTree(); final Document document = metadataXml.getDocumentTree();
final Element hmNode = document.getRootElement(); final Element hmNode = document.getRootElement();
@ -83,37 +85,79 @@ public void add(XmlDocument metadataXml) {
Set<String> entityNames = new HashSet<String>(); Set<String> entityNames = new HashSet<String>();
findClassNames( defaultPackage, hmNode, entityNames ); findClassNames( defaultPackage, hmNode, entityNames );
for ( String entity : entityNames ) { for ( String entity : entityNames ) {
hbmMetadataByEntityNameXRef.put( entity, metadataXml ); hbmMetadataByEntityNameXRef.put( entity, jaxbRoot );
} }
this.hbmMetadataToEntityNamesMap.put( metadataXml, entityNames ); this.hbmMetadataToEntityNamesMap.put( jaxbRoot, entityNames );
}
*/
public void add(HibernateMappingJaxbRoot jaxbRoot) {
final HibernateMapping hibernateMapping = jaxbRoot.getRoot();
String defaultPackage = MappingHelper.getStringValue( hibernateMapping.getPackage(), "" );
Set<String> entityNames = new HashSet<String>();
findClassNames( defaultPackage, jaxbRoot.getRoot().getClazzOrSubclassOrJoinedSubclass(), entityNames );
for ( String entity : entityNames ) {
hbmMetadataByEntityNameXRef.put( entity, jaxbRoot );
}
this.hbmMetadataToEntityNamesMap.put( jaxbRoot, entityNames );
} }
private void findClassNames(String defaultPackage, Element startNode, Set<String> names) { private void findClassNames(String defaultPackage, List entityClasses, Set<String> names) {
// if we have some extends we need to check if those classes possibly could be inside the // if we have some extends we need to check if those classes possibly could be inside the
// same hbm.xml file... // same hbm.xml file...
Iterator[] classes = new Iterator[4];
classes[0] = startNode.elementIterator( "class" );
classes[1] = startNode.elementIterator( "subclass" );
classes[2] = startNode.elementIterator( "joined-subclass" );
classes[3] = startNode.elementIterator( "union-subclass" );
Iterator classIterator = new JoinedIterator( classes ); // HibernateMapping.getClazzOrSubclassOrJoinedSubclass returns union-subclass objects
while ( classIterator.hasNext() ) { // as well as class, subclass, and joined-subclass objects
Element element = (Element) classIterator.next(); for ( Object entityClass : entityClasses) {
String entityName = element.attributeValue( "entity-name" ); String entityName;
if ( entityName == null ) { // TODO: can Class, Subclass, JoinedSubclass, and UnionSubclass implement the same interface
entityName = getClassName( element.attribute( "name" ), defaultPackage ); // so this stuff doesn't need to be duplicated?
if ( org.hibernate.metamodel.source.hbm.xml.mapping.Subclass.class.isInstance( entityClass ) ) {
org.hibernate.metamodel.source.hbm.xml.mapping.Subclass clazz = org.hibernate.metamodel.source.hbm.xml.mapping.Subclass.class.cast( entityClass );
names.add(
clazz.getEntityName() != null ?
clazz.getEntityName() :
getClassName( clazz.getName(), defaultPackage )
);
findClassNames( defaultPackage, clazz.getSubclass(), names );
}
else if ( org.hibernate.metamodel.source.hbm.xml.mapping.Class.class.isInstance( entityClass ) ) {
org.hibernate.metamodel.source.hbm.xml.mapping.Class clazz = org.hibernate.metamodel.source.hbm.xml.mapping.Class.class.cast( entityClass );
names.add(
clazz.getEntityName() != null ?
clazz.getEntityName() :
getClassName( clazz.getName(), defaultPackage )
);
findClassNames( defaultPackage, clazz.getSubclass(), names );
findClassNames( defaultPackage, clazz.getJoinedSubclass(), names );
findClassNames( defaultPackage, clazz.getUnionSubclass(), names );
}
else if ( org.hibernate.metamodel.source.hbm.xml.mapping.UnionSubclass.class.isInstance( entityClass ) ) {
org.hibernate.metamodel.source.hbm.xml.mapping.UnionSubclass clazz = org.hibernate.metamodel.source.hbm.xml.mapping.UnionSubclass.class.cast( entityClass );
names.add(
clazz.getEntityName() != null ?
clazz.getEntityName() :
getClassName( clazz.getName(), defaultPackage )
);
findClassNames( defaultPackage, clazz.getUnionSubclass(), names );
}
else if ( org.hibernate.metamodel.source.hbm.xml.mapping.JoinedSubclass.class.isInstance( entityClass ) ) {
org.hibernate.metamodel.source.hbm.xml.mapping.JoinedSubclass clazz = org.hibernate.metamodel.source.hbm.xml.mapping.JoinedSubclass.class.cast( entityClass );
names.add(
clazz.getEntityName() != null ?
clazz.getEntityName() :
getClassName( clazz.getName(), defaultPackage )
);
findClassNames( defaultPackage, clazz.getJoinedSubclass(), names );
}
else {
throw new InvalidMappingException( "unknown type of entity class", entityClass.getClass().getName() );
} }
names.add( entityName );
findClassNames( defaultPackage, element, names );
} }
} }
private String getClassName(Attribute name, String defaultPackage) { private String getClassName(String unqualifiedName, String defaultPackage) {
if ( name == null ) {
return null;
}
String unqualifiedName = name.getValue();
if ( unqualifiedName == null ) { if ( unqualifiedName == null ) {
return null; return null;
} }
@ -140,7 +184,7 @@ else if ( MetadataSourceType.CLASS.equals( type ) ) {
private void processHbmXmlQueue() { private void processHbmXmlQueue() {
LOG.debug( "Processing hbm.xml files" ); LOG.debug( "Processing hbm.xml files" );
for ( Map.Entry<XmlDocument, Set<String>> entry : hbmMetadataToEntityNamesMap.entrySet() ) { for ( Map.Entry<JaxbRoot, Set<String>> entry : hbmMetadataToEntityNamesMap.entrySet() ) {
// Unfortunately we have to create a Mappings instance for each iteration here // Unfortunately we have to create a Mappings instance for each iteration here
processHbmXml( entry.getKey(), entry.getValue() ); processHbmXml( entry.getKey(), entry.getValue() );
} }
@ -148,14 +192,14 @@ private void processHbmXmlQueue() {
hbmMetadataByEntityNameXRef.clear(); hbmMetadataByEntityNameXRef.clear();
} }
public void processHbmXml(XmlDocument metadataXml, Set<String> entityNames) { public void processHbmXml(JaxbRoot jaxbRoot, Set<String> entityNames) {
try { try {
metadata.getHibernateXmlBinder().bindRoot( metadataXml, entityNames ); metadata.getHibernateXmlBinder().bindRoot( jaxbRoot, entityNames );
} }
catch ( MappingException me ) { catch ( MappingException me ) {
throw new InvalidMappingException( throw new InvalidMappingException(
metadataXml.getOrigin().getType(), jaxbRoot.getOrigin().getType().toString(),
metadataXml.getOrigin().getName(), jaxbRoot.getOrigin().getName(),
me me
); );
} }

View File

@ -0,0 +1,115 @@
/*
* 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.util;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.dom4j.Element;
import org.hibernate.internal.util.ReflectHelper;
/**
* Helper class for working with DOM documents.
*
* @author Gail Badner
*/
public class MappingHelper {
private MappingHelper() {
}
public static String extractAttributeValue(Element element, String attributeName) {
return extractAttributeValue( element, attributeName, null );
}
public static String extractAttributeValue(Element element, String attributeName, String defaultValue) {
String attributeValue = ( element == null ? null : element.attributeValue( attributeName ) );
return attributeValue == null ? defaultValue : attributeValue;
}
public static String getStringValue(String value, String defaultValue) {
return value == null ? defaultValue : value;
}
public static int extractIntAttributeValue(Element element, String attributeName) {
return extractIntAttributeValue( element, attributeName, -1 );
}
public static int extractIntAttributeValue(Element element, String attributeName, int defaultValue) {
String attributeValue = ( element == null ? null : element.attributeValue( attributeName ) );
return attributeValue == null ? defaultValue : Integer.valueOf( attributeValue );
}
public static int getIntValue(String value, int defaultValue) {
return value == null ? defaultValue : Integer.parseInt( value );
}
public static boolean extractBooleanAttributeValue(Element element, String attributeName) {
return extractBooleanAttributeValue( element, attributeName, false );
}
public static boolean extractBooleanAttributeValue(Element element, String attributeName, boolean defaultValue) {
String attributeValue = ( element == null ? null : element.attributeValue( attributeName ) );
return attributeValue == null ? defaultValue : Boolean.valueOf( attributeValue );
}
public static boolean getBooleanValue(String value, boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf( value );
}
public static Class extractClassAttributeValue(Element element, String attributeName)
throws ClassNotFoundException {
String attributeValue = ( element == null ? null : element.attributeValue( attributeName ) );
return (
attributeValue == null ?
null :
ReflectHelper.classForName( attributeValue )
);
}
public static Class getClassValue(String className)
throws ClassNotFoundException {
return (
className == null ?
null :
ReflectHelper.classForName( className )
);
}
public static Set<String> getStringValueTokens(String str, String delimiters) {
if ( str == null ) {
return Collections.emptySet();
}
else {
StringTokenizer tokenizer = new StringTokenizer( str, delimiters );
Set<String> tokens = new HashSet<String>();
while ( tokenizer.hasMoreTokens() ) {
tokens.add( tokenizer.nextToken() );
}
return tokens;
}
}
}

View File

@ -31,7 +31,8 @@
import org.hibernate.internal.util.xml.Origin; import org.hibernate.internal.util.xml.Origin;
import org.hibernate.internal.util.xml.XMLHelper; import org.hibernate.internal.util.xml.XMLHelper;
import org.hibernate.internal.util.xml.XmlDocument; import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.metamodel.source.MetadataSources; import org.hibernate.metamodel.source.hbm.xml.mapping.HibernateMapping;
import org.hibernate.metamodel.source.internal.JaxbRoot;
import org.hibernate.metamodel.source.internal.MetadataImpl; import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.junit.Test; import org.junit.Test;
@ -47,45 +48,35 @@ public class BasicHbmBindingTests extends AbstractBasicBindingTests {
private static final Logger log = Logger.getLogger( BasicHbmBindingTests.class.getName() ); private static final Logger log = Logger.getLogger( BasicHbmBindingTests.class.getName() );
public EntityBinding buildSimpleEntityBinding() { public EntityBinding buildSimpleEntityBinding() {
MetadataImpl metadata = (MetadataImpl) new MetadataSources( basicServiceRegistry() ).buildMetadata(); return getEntityBinding(
"org/hibernate/metamodel/binding/SimpleEntity.hbm.xml",
XmlDocument xmlDocument = readResource( "/org/hibernate/metamodel/binding/SimpleEntity.hbm.xml" ); SimpleEntity.class
metadata.getHibernateXmlBinder().bindRoot( xmlDocument ); );
return metadata.getEntityBinding( SimpleEntity.class.getName() );
} }
public EntityBinding buildSimpleVersionedEntityBinding() { public EntityBinding buildSimpleVersionedEntityBinding() {
MetadataImpl metadata = (MetadataImpl) new MetadataSources( basicServiceRegistry() ).buildMetadata(); return getEntityBinding(
"org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml",
String fileName = "/org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml"; SimpleVersionedEntity.class
XmlDocument xmlDocument = readResource( fileName ); );
metadata.getHibernateXmlBinder().bindRoot( xmlDocument );
return metadata.getEntityBinding( SimpleVersionedEntity.class.getName() );
} }
@Test @Test
@SuppressWarnings({ "unchecked" })
public void testJaxbApproach() { public void testJaxbApproach() {
final String resourceName = "org/hibernate/metamodel/binding/SimpleVersionedEntity.xml"; final String resourceName = "org/hibernate/metamodel/binding/SimpleVersionedEntity.xml";
metadata.addResource( resourceName );
MetadataSources metadataSources = new MetadataSources( basicServiceRegistry() ); assertEquals( 1, metadata.getJaxbRootList().size() );
metadataSources.addResource( resourceName ); JaxbRoot jaxbRoot = metadata.getJaxbRootList().get( 0 );
assertEquals( 1, metadataSources.getJaxbRootList().size() ); metadata.getHibernateXmlBinder().bindRoot( jaxbRoot );
} }
private XmlDocument readResource(final String name) { private EntityBinding getEntityBinding(String resourceName, Class entityClass ) {
Origin origin = new Origin() { final MetadataImpl metadata = new MetadataImpl( basicServiceRegistry() );
@Override metadata.addResource( resourceName );
public String getType() { assertEquals( 1, metadata.getJaxbRootList().size() );
return "resource"; JaxbRoot jaxbRoot = metadata.getJaxbRootList().get( 0 );
} metadata.getHibernateXmlBinder().bindRoot( jaxbRoot );
return metadata.getEntityBinding( entityClass.getName() );
@Override
public String getName() {
return name;
}
};
InputSource inputSource = new InputSource( ConfigHelper.getResourceAsStream( name ) );
return MappingReader.INSTANCE.readMappingDocument( XMLHelper.DEFAULT_DTD_RESOLVER, inputSource, origin );
} }
} }

View File

@ -1,9 +1,7 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC <hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<hibernate-mapping package="org.hibernate.metamodel.binding">
<class name="EntityWithCollection"> <class name="EntityWithCollection">

View File

@ -1,9 +1,7 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC <hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<hibernate-mapping package="org.hibernate.metamodel.binding">
<class name="SimpleEntity"> <class name="SimpleEntity">

View File

@ -22,11 +22,9 @@
~ 51 Franklin Street, Fifth Floor ~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA ~ Boston, MA 02110-1301 USA
--> -->
<!DOCTYPE hibernate-mapping PUBLIC <hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<hibernate-mapping package="org.hibernate.metamodel.binding">
<class name="SimpleVersionedEntity"> <class name="SimpleVersionedEntity">