Search in sources :

Example 66 with Property

use of org.hibernate.mapping.Property in project hibernate-orm by hibernate.

the class ModelBinder method createPluralAttribute.

private Property createPluralAttribute(MappingDocument sourceDocument, PluralAttributeSource attributeSource, PersistentClass entityDescriptor) {
    final Collection collectionBinding;
    if (attributeSource instanceof PluralAttributeSourceListImpl) {
        collectionBinding = new org.hibernate.mapping.List(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        registerSecondPass(new PluralAttributeListSecondPass(sourceDocument, (IndexedPluralAttributeSource) attributeSource, (org.hibernate.mapping.List) collectionBinding), sourceDocument);
    } else if (attributeSource instanceof PluralAttributeSourceSetImpl) {
        collectionBinding = new Set(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        registerSecondPass(new PluralAttributeSetSecondPass(sourceDocument, attributeSource, collectionBinding), sourceDocument);
    } else if (attributeSource instanceof PluralAttributeSourceMapImpl) {
        collectionBinding = new org.hibernate.mapping.Map(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        registerSecondPass(new PluralAttributeMapSecondPass(sourceDocument, (IndexedPluralAttributeSource) attributeSource, (org.hibernate.mapping.Map) collectionBinding), sourceDocument);
    } else if (attributeSource instanceof PluralAttributeSourceBagImpl) {
        collectionBinding = new Bag(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        registerSecondPass(new PluralAttributeBagSecondPass(sourceDocument, attributeSource, collectionBinding), sourceDocument);
    } else if (attributeSource instanceof PluralAttributeSourceIdBagImpl) {
        collectionBinding = new IdentifierBag(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        registerSecondPass(new PluralAttributeIdBagSecondPass(sourceDocument, attributeSource, collectionBinding), sourceDocument);
    } else if (attributeSource instanceof PluralAttributeSourceArrayImpl) {
        final PluralAttributeSourceArray arraySource = (PluralAttributeSourceArray) attributeSource;
        collectionBinding = new Array(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        ((Array) collectionBinding).setElementClassName(sourceDocument.qualifyClassName(arraySource.getElementClass()));
        registerSecondPass(new PluralAttributeArraySecondPass(sourceDocument, arraySource, (Array) collectionBinding), sourceDocument);
    } else if (attributeSource instanceof PluralAttributeSourcePrimitiveArrayImpl) {
        collectionBinding = new PrimitiveArray(sourceDocument.getMetadataCollector(), entityDescriptor);
        bindCollectionMetadata(sourceDocument, attributeSource, collectionBinding);
        registerSecondPass(new PluralAttributePrimitiveArraySecondPass(sourceDocument, (IndexedPluralAttributeSource) attributeSource, (PrimitiveArray) collectionBinding), sourceDocument);
    } else {
        throw new AssertionFailure("Unexpected PluralAttributeSource type : " + attributeSource.getClass().getName());
    }
    sourceDocument.getMetadataCollector().addCollectionBinding(collectionBinding);
    final Property attribute = new Property();
    attribute.setValue(collectionBinding);
    bindProperty(sourceDocument, attributeSource, attribute);
    return attribute;
}
Also used : Set(org.hibernate.mapping.Set) ArrayList(java.util.ArrayList) List(java.util.List) Property(org.hibernate.mapping.Property) SyntheticProperty(org.hibernate.mapping.SyntheticProperty) AssertionFailure(org.hibernate.AssertionFailure) Bag(org.hibernate.mapping.Bag) IdentifierBag(org.hibernate.mapping.IdentifierBag) IdentifierBag(org.hibernate.mapping.IdentifierBag) PrimitiveArray(org.hibernate.mapping.PrimitiveArray) PluralAttributeSourceArray(org.hibernate.boot.model.source.spi.PluralAttributeSourceArray) Array(org.hibernate.mapping.Array) PluralAttributeSourceArray(org.hibernate.boot.model.source.spi.PluralAttributeSourceArray) PrimitiveArray(org.hibernate.mapping.PrimitiveArray) Collection(org.hibernate.mapping.Collection) IndexedCollection(org.hibernate.mapping.IndexedCollection) IdentifierCollection(org.hibernate.mapping.IdentifierCollection) Map(java.util.Map) HashMap(java.util.HashMap)

Example 67 with Property

use of org.hibernate.mapping.Property in project hibernate-orm by hibernate.

the class ModelBinder method createManyToOneAttribute.

private Property createManyToOneAttribute(MappingDocument sourceDocument, SingularAttributeSourceManyToOne manyToOneSource, ManyToOne manyToOneBinding, String containingClassName) {
    final String attributeName = manyToOneSource.getName();
    final String referencedEntityName;
    if (manyToOneSource.getReferencedEntityName() != null) {
        referencedEntityName = manyToOneSource.getReferencedEntityName();
    } else {
        Class reflectedPropertyClass = Helper.reflectedPropertyClass(sourceDocument, containingClassName, attributeName);
        if (reflectedPropertyClass != null) {
            referencedEntityName = reflectedPropertyClass.getName();
        } else {
            prepareValueTypeViaReflection(sourceDocument, manyToOneBinding, containingClassName, attributeName, manyToOneSource.getAttributeRole());
            referencedEntityName = manyToOneBinding.getTypeName();
        }
    }
    if (manyToOneSource.isUnique()) {
        manyToOneBinding.markAsLogicalOneToOne();
    }
    bindManyToOneAttribute(sourceDocument, manyToOneSource, manyToOneBinding, referencedEntityName);
    final String propertyRef = manyToOneBinding.getReferencedPropertyName();
    if (propertyRef != null) {
        handlePropertyReference(sourceDocument, manyToOneBinding.getReferencedEntityName(), propertyRef, true, "<many-to-one name=\"" + manyToOneSource.getName() + "\"/>");
    }
    Property prop = new Property();
    prop.setValue(manyToOneBinding);
    bindProperty(sourceDocument, manyToOneSource, prop);
    if (StringHelper.isNotEmpty(manyToOneSource.getCascadeStyleName())) {
        // a "validation" fails since it loses "context"
        if (manyToOneSource.getCascadeStyleName().contains("delete-orphan")) {
            if (!manyToOneBinding.isLogicalOneToOne()) {
                throw new MappingException(String.format(Locale.ENGLISH, "many-to-one attribute [%s] specified delete-orphan but is not specified as unique; " + "remove delete-orphan cascading or specify unique=\"true\"", manyToOneSource.getAttributeRole().getFullPath()), sourceDocument.getOrigin());
            }
        }
    }
    return prop;
}
Also used : PersistentClass(org.hibernate.mapping.PersistentClass) RootClass(org.hibernate.mapping.RootClass) Property(org.hibernate.mapping.Property) SyntheticProperty(org.hibernate.mapping.SyntheticProperty) MappingException(org.hibernate.boot.MappingException)

Example 68 with Property

use of org.hibernate.mapping.Property in project hibernate-orm by hibernate.

the class ModelBinder method createBasicAttribute.

private Property createBasicAttribute(MappingDocument sourceDocument, final SingularAttributeSourceBasic attributeSource, SimpleValue value, String containingClassName) {
    final String attributeName = attributeSource.getName();
    bindSimpleValueType(sourceDocument, attributeSource.getTypeInformation(), value);
    relationalObjectBinder.bindColumnsAndFormulas(sourceDocument, attributeSource.getRelationalValueSources(), value, attributeSource.areValuesNullableByDefault(), new RelationalObjectBinder.ColumnNamingDelegate() {

        @Override
        public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
            return implicitNamingStrategy.determineBasicColumnName(attributeSource);
        }
    });
    prepareValueTypeViaReflection(sourceDocument, value, containingClassName, attributeName, attributeSource.getAttributeRole());
    //		// this is done here 'cos we might only know the type here (ugly!)
    //		// TODO: improve this a lot:
    //		if ( value instanceof ToOne ) {
    //			ToOne toOne = (ToOne) value;
    //			String propertyRef = toOne.getReferencedEntityAttributeName();
    //			if ( propertyRef != null ) {
    //				mappings.addUniquePropertyReference( toOne.getReferencedEntityName(), propertyRef );
    //			}
    //			toOne.setCascadeDeleteEnabled( "cascade".equals( subnode.attributeValue( "on-delete" ) ) );
    //		}
    //		else if ( value instanceof Collection ) {
    //			Collection coll = (Collection) value;
    //			String propertyRef = coll.getReferencedEntityAttributeName();
    //			// not necessarily a *unique* property reference
    //			if ( propertyRef != null ) {
    //				mappings.addPropertyReference( coll.getOwnerEntityName(), propertyRef );
    //			}
    //		}
    value.createForeignKey();
    Property property = new Property();
    property.setValue(value);
    bindProperty(sourceDocument, attributeSource, property);
    return property;
}
Also used : Identifier(org.hibernate.boot.model.naming.Identifier) LocalMetadataBuildingContext(org.hibernate.boot.model.source.spi.LocalMetadataBuildingContext) Property(org.hibernate.mapping.Property) SyntheticProperty(org.hibernate.mapping.SyntheticProperty)

Example 69 with Property

use of org.hibernate.mapping.Property in project hibernate-orm by hibernate.

the class ResultSetMappingBinder method extractPropertyResults.

@SuppressWarnings("unchecked")
private static Map<String, String[]> extractPropertyResults(String alias, NativeQueryNonScalarRootReturn rtnSource, PersistentClass pc, HbmLocalMetadataBuildingContext context) {
    if (CollectionHelper.isEmpty(rtnSource.getReturnProperty())) {
        return null;
    }
    final HashMap results = new HashMap();
    List<JaxbHbmNativeQueryPropertyReturnType> propertyReturnSources = new ArrayList<JaxbHbmNativeQueryPropertyReturnType>();
    List<String> propertyNames = new ArrayList<String>();
    for (JaxbHbmNativeQueryPropertyReturnType propertyReturnSource : rtnSource.getReturnProperty()) {
        final int dotPosition = propertyReturnSource.getName().lastIndexOf('.');
        if (pc == null || dotPosition == -1) {
            propertyReturnSources.add(propertyReturnSource);
            propertyNames.add(propertyReturnSource.getName());
        } else {
            final String reducedName = propertyReturnSource.getName().substring(0, dotPosition);
            final Value value = pc.getRecursiveProperty(reducedName).getValue();
            Iterator parentPropItr;
            if (value instanceof Component) {
                final Component comp = (Component) value;
                parentPropItr = comp.getPropertyIterator();
            } else if (value instanceof ToOne) {
                final ToOne toOne = (ToOne) value;
                final PersistentClass referencedPc = context.getMetadataCollector().getEntityBinding(toOne.getReferencedEntityName());
                if (toOne.getReferencedPropertyName() != null) {
                    try {
                        parentPropItr = ((Component) referencedPc.getRecursiveProperty(toOne.getReferencedPropertyName()).getValue()).getPropertyIterator();
                    } catch (ClassCastException e) {
                        throw new MappingException("dotted notation reference neither a component nor a many/one to one", e, context.getOrigin());
                    }
                } else {
                    try {
                        if (referencedPc.getIdentifierMapper() == null) {
                            parentPropItr = ((Component) referencedPc.getIdentifierProperty().getValue()).getPropertyIterator();
                        } else {
                            parentPropItr = referencedPc.getIdentifierMapper().getPropertyIterator();
                        }
                    } catch (ClassCastException e) {
                        throw new MappingException("dotted notation reference neither a component nor a many/one to one", e, context.getOrigin());
                    }
                }
            } else {
                throw new MappingException("dotted notation reference neither a component nor a many/one to one", context.getOrigin());
            }
            boolean hasFollowers = false;
            List<String> followers = new ArrayList<String>();
            while (parentPropItr.hasNext()) {
                final Property parentProperty = (Property) parentPropItr.next();
                final String currentPropertyName = parentProperty.getName();
                final String currentName = reducedName + '.' + currentPropertyName;
                if (hasFollowers) {
                    followers.add(currentName);
                }
                if (propertyReturnSource.getName().equals(currentName)) {
                    hasFollowers = true;
                }
            }
            int index = propertyNames.size();
            for (String follower : followers) {
                int currentIndex = getIndexOfFirstMatchingProperty(propertyNames, follower);
                index = currentIndex != -1 && currentIndex < index ? currentIndex : index;
            }
            propertyNames.add(index, propertyReturnSource.getName());
            propertyReturnSources.add(index, propertyReturnSource);
        }
    }
    Set<String> uniqueReturnProperty = new HashSet<String>();
    for (JaxbHbmNativeQueryPropertyReturnType propertyReturnBinding : propertyReturnSources) {
        final String name = propertyReturnBinding.getName();
        if ("class".equals(name)) {
            throw new MappingException("class is not a valid property name to use in a <return-property>, use <return-discriminator> instead", context.getOrigin());
        }
        //TODO: validate existing of property with the chosen name. (secondpass )
        ArrayList allResultColumns = extractResultColumns(propertyReturnBinding);
        if (allResultColumns.isEmpty()) {
            throw new MappingException(String.format(Locale.ENGLISH, "return-property [alias=%s, property=%s] must specify at least one column or return-column name", alias, propertyReturnBinding.getName()), context.getOrigin());
        }
        if (uniqueReturnProperty.contains(name)) {
            throw new MappingException(String.format(Locale.ENGLISH, "Duplicate return-property [alias=%s] : %s", alias, propertyReturnBinding.getName()), context.getOrigin());
        }
        uniqueReturnProperty.add(name);
        // the issue here is that for <return-join/> representing an entity collection,
        // the collection element values (the property values of the associated entity)
        // are represented as 'element.{propertyname}'.  Thus the StringHelper.root()
        // here puts everything under 'element' (which additionally has significant
        // meaning).  Probably what we need to do is to something like this instead:
        //      String root = StringHelper.root( name );
        //      String key = root; // by default
        //      if ( !root.equals( name ) ) {
        //	        // we had a dot
        //          if ( !root.equals( alias ) {
        //              // the root does not apply to the specific alias
        //              if ( "elements".equals( root ) {
        //                  // we specifically have a <return-join/> representing an entity collection
        //                  // and this <return-property/> is one of that entity's properties
        //                  key = name;
        //              }
        //          }
        //      }
        // but I am not clear enough on the intended purpose of this code block, especially
        // in relation to the "Reorder properties" code block above...
        //			String key = StringHelper.root( name );
        ArrayList intermediateResults = (ArrayList) results.get(name);
        if (intermediateResults == null) {
            results.put(name, allResultColumns);
        } else {
            intermediateResults.addAll(allResultColumns);
        }
    }
    for (Object o : results.entrySet()) {
        Map.Entry entry = (Map.Entry) o;
        if (entry.getValue() instanceof ArrayList) {
            ArrayList list = (ArrayList) entry.getValue();
            entry.setValue(list.toArray(new String[list.size()]));
        }
    }
    return results.isEmpty() ? Collections.EMPTY_MAP : results;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JaxbHbmNativeQueryPropertyReturnType(org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNativeQueryPropertyReturnType) MappingException(org.hibernate.boot.MappingException) Value(org.hibernate.mapping.Value) Iterator(java.util.Iterator) ToOne(org.hibernate.mapping.ToOne) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) HashMap(java.util.HashMap) Map(java.util.Map) PersistentClass(org.hibernate.mapping.PersistentClass) HashSet(java.util.HashSet)

Example 70 with Property

use of org.hibernate.mapping.Property in project hibernate-orm by hibernate.

the class DDLTest method testNotNullOnlyAppliedIfEmbeddedIsNotNullItself.

@Test
public void testNotNullOnlyAppliedIfEmbeddedIsNotNullItself() throws Exception {
    PersistentClass classMapping = metadata().getEntityBinding(Tv.class.getName());
    Property property = classMapping.getProperty("tuner.frequency");
    Column serialColumn = (Column) property.getColumnIterator().next();
    assertEquals("Validator annotations are applied on tuner as it is @NotNull", false, serialColumn.isNullable());
    property = classMapping.getProperty("recorder.time");
    serialColumn = (Column) property.getColumnIterator().next();
    assertEquals("Validator annotations are applied on tuner as it is @NotNull", true, serialColumn.isNullable());
}
Also used : Column(org.hibernate.mapping.Column) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Aggregations

Property (org.hibernate.mapping.Property)94 PersistentClass (org.hibernate.mapping.PersistentClass)53 Component (org.hibernate.mapping.Component)30 Test (org.junit.Test)29 SimpleValue (org.hibernate.mapping.SimpleValue)24 Iterator (java.util.Iterator)23 SyntheticProperty (org.hibernate.mapping.SyntheticProperty)18 MetadataSources (org.hibernate.boot.MetadataSources)17 Column (org.hibernate.mapping.Column)17 AnnotationException (org.hibernate.AnnotationException)14 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)14 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)14 XProperty (org.hibernate.annotations.common.reflection.XProperty)12 Metadata (org.hibernate.boot.Metadata)11 Collection (org.hibernate.mapping.Collection)11 HashMap (java.util.HashMap)10 AssertionFailure (org.hibernate.AssertionFailure)10 MappingException (org.hibernate.MappingException)9 TestForIssue (org.hibernate.testing.TestForIssue)9 Map (java.util.Map)7