Search in sources :

Example 36 with Component

use of org.hibernate.mapping.Component 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 37 with Component

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

the class TypeSafeActivator method applyDDL.

private static void applyDDL(String prefix, PersistentClass persistentClass, Class<?> clazz, ValidatorFactory factory, Set<Class<?>> groups, boolean activateNotNull, Dialect dialect) {
    final BeanDescriptor descriptor = factory.getValidator().getConstraintsForClass(clazz);
    for (PropertyDescriptor propertyDesc : descriptor.getConstrainedProperties()) {
        Property property = findPropertyByName(persistentClass, prefix + propertyDesc.getPropertyName());
        boolean hasNotNull;
        if (property != null) {
            hasNotNull = applyConstraints(propertyDesc.getConstraintDescriptors(), property, propertyDesc, groups, activateNotNull, dialect);
            if (property.isComposite() && propertyDesc.isCascaded()) {
                Class<?> componentClass = ((Component) property.getValue()).getComponentClass();
                /*
					 * we can apply not null if the upper component let's us activate not null
					 * and if the property is not null.
					 * Otherwise, all sub columns should be left nullable
					 */
                final boolean canSetNotNullOnColumns = activateNotNull && hasNotNull;
                applyDDL(prefix + propertyDesc.getPropertyName() + ".", persistentClass, componentClass, factory, groups, canSetNotNullOnColumns, dialect);
            }
        //FIXME add collection of components
        }
    }
}
Also used : PropertyDescriptor(javax.validation.metadata.PropertyDescriptor) BeanDescriptor(javax.validation.metadata.BeanDescriptor) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property)

Example 38 with Component

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

the class TypeSafeActivator method findPropertyByName.

/**
	 * Locate the property by path in a recursive way, including IdentifierProperty in the loop if propertyName is
	 * {@code null}.  If propertyName is {@code null} or empty, the IdentifierProperty is returned
	 */
private static Property findPropertyByName(PersistentClass associatedClass, String propertyName) {
    Property property = null;
    Property idProperty = associatedClass.getIdentifierProperty();
    String idName = idProperty != null ? idProperty.getName() : null;
    try {
        if (propertyName == null || propertyName.length() == 0 || propertyName.equals(idName)) {
            //default to id
            property = idProperty;
        } else {
            if (propertyName.indexOf(idName + ".") == 0) {
                property = idProperty;
                propertyName = propertyName.substring(idName.length() + 1);
            }
            StringTokenizer st = new StringTokenizer(propertyName, ".", false);
            while (st.hasMoreElements()) {
                String element = (String) st.nextElement();
                if (property == null) {
                    property = associatedClass.getProperty(element);
                } else {
                    if (!property.isComposite()) {
                        return null;
                    }
                    property = ((Component) property.getValue()).getProperty(element);
                }
            }
        }
    } catch (MappingException e) {
        try {
            //if we do not find it try to check the identifier mapper
            if (associatedClass.getIdentifierMapper() == null) {
                return null;
            }
            StringTokenizer st = new StringTokenizer(propertyName, ".", false);
            while (st.hasMoreElements()) {
                String element = (String) st.nextElement();
                if (property == null) {
                    property = associatedClass.getIdentifierMapper().getProperty(element);
                } else {
                    if (!property.isComposite()) {
                        return null;
                    }
                    property = ((Component) property.getValue()).getProperty(element);
                }
            }
        } catch (MappingException ee) {
            return null;
        }
    }
    return property;
}
Also used : StringTokenizer(java.util.StringTokenizer) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) MappingException(org.hibernate.MappingException)

Example 39 with Component

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

the class NestedEmbeddableMetadataTest method testEnumTypeInterpretation.

@Test
public void testEnumTypeInterpretation() {
    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().enableAutoClose().applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop").build();
    try {
        final Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(Customer.class).buildMetadata();
        PersistentClass classMetadata = metadata.getEntityBinding(Customer.class.getName());
        Property investmentsProperty = classMetadata.getProperty("investments");
        Collection investmentsValue = (Collection) investmentsProperty.getValue();
        Component investmentMetadata = (Component) investmentsValue.getElement();
        Value descriptionValue = investmentMetadata.getProperty("description").getValue();
        assertEquals(1, descriptionValue.getColumnSpan());
        Column selectable = (Column) descriptionValue.getColumnIterator().next();
        assertEquals(500, selectable.getLength());
        Component amountMetadata = (Component) investmentMetadata.getProperty("amount").getValue();
        SimpleValue currencyMetadata = (SimpleValue) amountMetadata.getProperty("currency").getValue();
        CustomType currencyType = (CustomType) currencyMetadata.getType();
        int[] currencySqlTypes = currencyType.sqlTypes(metadata);
        assertEquals(1, currencySqlTypes.length);
        assertJdbcTypeCode(Types.VARCHAR, currencySqlTypes[0]);
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
Also used : CustomType(org.hibernate.type.CustomType) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) SimpleValue(org.hibernate.mapping.SimpleValue) Column(org.hibernate.mapping.Column) SimpleValue(org.hibernate.mapping.SimpleValue) Value(org.hibernate.mapping.Value) Collection(org.hibernate.mapping.Collection) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test)

Example 40 with Component

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

the class FieldAccessedNestedEmbeddableMetadataTest method testEnumTypeInterpretation.

@Test
@FailureExpected(jiraKey = "HHH-9089")
public void testEnumTypeInterpretation() {
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
    try {
        final Metadata metadata = new MetadataSources(ssr).addAnnotatedClass(Customer.class).buildMetadata();
        PersistentClass classMetadata = metadata.getEntityBinding(Customer.class.getName());
        Property investmentsProperty = classMetadata.getProperty("investments");
        Collection investmentsValue = (Collection) investmentsProperty.getValue();
        Component investmentMetadata = (Component) investmentsValue.getElement();
        Value descriptionValue = investmentMetadata.getProperty("description").getValue();
        assertEquals(1, descriptionValue.getColumnSpan());
        Column selectable = (Column) descriptionValue.getColumnIterator().next();
        assertEquals(500, selectable.getLength());
        Component amountMetadata = (Component) investmentMetadata.getProperty("amount").getValue();
        SimpleValue currencyMetadata = (SimpleValue) amountMetadata.getProperty("currency").getValue();
        CustomType currencyType = (CustomType) currencyMetadata.getType();
        int[] currencySqlTypes = currencyType.sqlTypes(metadata);
        assertEquals(1, currencySqlTypes.length);
        assertJdbcTypeCode(Types.VARCHAR, currencySqlTypes[0]);
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : CustomType(org.hibernate.type.CustomType) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) SimpleValue(org.hibernate.mapping.SimpleValue) Column(org.hibernate.mapping.Column) SimpleValue(org.hibernate.mapping.SimpleValue) Value(org.hibernate.mapping.Value) Collection(org.hibernate.mapping.Collection) Component(org.hibernate.mapping.Component) Property(org.hibernate.mapping.Property) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) PersistentClass(org.hibernate.mapping.PersistentClass) Test(org.junit.Test) FailureExpected(org.hibernate.testing.FailureExpected)

Aggregations

Component (org.hibernate.mapping.Component)42 Property (org.hibernate.mapping.Property)29 PersistentClass (org.hibernate.mapping.PersistentClass)17 Iterator (java.util.Iterator)11 AnnotationException (org.hibernate.AnnotationException)9 SimpleValue (org.hibernate.mapping.SimpleValue)9 XProperty (org.hibernate.annotations.common.reflection.XProperty)8 ManyToOne (org.hibernate.mapping.ManyToOne)8 Value (org.hibernate.mapping.Value)8 HashMap (java.util.HashMap)6 Collection (org.hibernate.mapping.Collection)6 ArrayList (java.util.ArrayList)5 AssertionFailure (org.hibernate.AssertionFailure)5 MappingException (org.hibernate.MappingException)5 Any (org.hibernate.mapping.Any)5 Column (org.hibernate.mapping.Column)5 Join (org.hibernate.mapping.Join)5 XClass (org.hibernate.annotations.common.reflection.XClass)4 SyntheticProperty (org.hibernate.mapping.SyntheticProperty)4 Ejb3Column (org.hibernate.cfg.Ejb3Column)3