Example usage for org.hibernate.mapping Property getName

List of usage examples for org.hibernate.mapping Property getName

Introduction

In this page you can find the example usage for org.hibernate.mapping Property getName.

Prototype

public String getName() 

Source Link

Usage

From source file:org.libreplan.business.common.LibrePlanClassValidator.java

License:Open Source License

/**
 * Retrieve the property by path in a recursive way, including IndetifierProperty in the loop
 * If propertyName is null or empty, the IdentifierProperty is returned
 *//* w  ww  .  j  ava2  s .c  om*/
public 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;
}

From source file:org.sparkcommerce.openadmin.server.dao.DynamicEntityDaoImpl.java

License:Apache License

protected Map<String, FieldMetadata> getPropertiesForEntityClass(Class<?> targetClass, ForeignKey foreignField,
        String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields,
        MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, String[] includeFields,
        String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname,
        List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded) {
    Map<String, FieldMetadata> presentationAttributes = metadata.getFieldPresentationAttributes(null,
            targetClass, this, "");
    if (isParentExcluded) {
        for (String key : presentationAttributes.keySet()) {
            LOG.debug("getPropertiesForEntityClass:Excluding " + key + " because parent is excluded.");
            presentationAttributes.get(key).setExcluded(true);
        }//from  ww w .j ava2 s .  c o  m
    }

    Map idMetadata = getIdMetadata(targetClass);
    Map<String, FieldMetadata> fields = new HashMap<String, FieldMetadata>();
    String idProperty = (String) idMetadata.get("name");
    List<String> propertyNames = getPropertyNames(targetClass);
    propertyNames.add(idProperty);
    Type idType = (Type) idMetadata.get("type");
    List<Type> propertyTypes = getPropertyTypes(targetClass);
    propertyTypes.add(idType);

    PersistentClass persistentClass = getPersistentClass(targetClass.getName());
    Iterator testIter = persistentClass.getPropertyIterator();
    List<Property> propertyList = new ArrayList<Property>();

    //check the properties for problems
    while (testIter.hasNext()) {
        Property property = (Property) testIter.next();
        if (property.getName().contains(".")) {
            throw new IllegalArgumentException(
                    "Properties from entities that utilize a period character ('.') in their name are incompatible with this system. The property name in question is: ("
                            + property.getName() + ") from the class: (" + targetClass.getName() + ")");
        }
        propertyList.add(property);
    }

    buildProperties(targetClass, foreignField, additionalForeignFields, additionalNonPersistentProperties,
            mergedPropertyType, presentationAttributes, propertyList, fields, propertyNames, propertyTypes,
            idProperty, populateManyToOneFields, includeFields, excludeFields, configurationKey,
            ceilingEntityFullyQualifiedClassname, parentClasses, prefix, isParentExcluded, false);
    BasicFieldMetadata presentationAttribute = new BasicFieldMetadata();
    presentationAttribute.setExplicitFieldType(SupportedFieldType.STRING);
    presentationAttribute.setVisibility(VisibilityEnum.HIDDEN_ALL);
    if (!ArrayUtils.isEmpty(additionalNonPersistentProperties)) {
        Class<?>[] entities = getAllPolymorphicEntitiesFromCeiling(targetClass);
        for (String additionalNonPersistentProperty : additionalNonPersistentProperties) {
            if (StringUtils.isEmpty(prefix)
                    || (!StringUtils.isEmpty(prefix) && additionalNonPersistentProperty.startsWith(prefix))) {
                String myAdditionalNonPersistentProperty = additionalNonPersistentProperty;
                //get final property if this is a dot delimited property
                int finalDotPos = additionalNonPersistentProperty.lastIndexOf('.');
                if (finalDotPos >= 0) {
                    myAdditionalNonPersistentProperty = myAdditionalNonPersistentProperty
                            .substring(finalDotPos + 1, myAdditionalNonPersistentProperty.length());
                }
                //check all the polymorphic types on this target class to see if the end property exists
                Field testField = null;
                Method testMethod = null;
                for (Class<?> clazz : entities) {
                    try {
                        testMethod = clazz.getMethod(myAdditionalNonPersistentProperty);
                        if (testMethod != null) {
                            break;
                        }
                    } catch (NoSuchMethodException e) {
                        //do nothing - method does not exist
                    }
                    testField = getFieldManager().getField(clazz, myAdditionalNonPersistentProperty);
                    if (testField != null) {
                        break;
                    }
                }
                //if the property exists, add it to the metadata for this class
                if (testField != null || testMethod != null) {
                    fields.put(additionalNonPersistentProperty,
                            metadata.getFieldMetadata(prefix, additionalNonPersistentProperty, propertyList,
                                    SupportedFieldType.STRING, null, targetClass, presentationAttribute,
                                    mergedPropertyType, this));
                }
            }
        }
    }

    return fields;
}

From source file:org.sparkcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider.java

License:Apache License

@Override
public FieldProviderResponse addMetadataFromMappingData(
        AddMetadataFromMappingDataRequest addMetadataFromMappingDataRequest, FieldMetadata metadata) {
    BasicFieldMetadata fieldMetadata = (BasicFieldMetadata) metadata;
    fieldMetadata.setFieldType(addMetadataFromMappingDataRequest.getType());
    fieldMetadata.setSecondaryType(addMetadataFromMappingDataRequest.getSecondaryType());
    if (addMetadataFromMappingDataRequest.getRequestedEntityType() != null
            && !addMetadataFromMappingDataRequest.getRequestedEntityType().isCollectionType()) {
        Column column = null;/*  w w w .j  a v a2 s  .c  om*/
        for (Property property : addMetadataFromMappingDataRequest.getComponentProperties()) {
            if (property.getName().equals(addMetadataFromMappingDataRequest.getPropertyName())) {
                Object columnObject = property.getColumnIterator().next();
                if (columnObject instanceof Column) {
                    column = (Column) columnObject;
                }
                break;
            }
        }
        if (column != null) {
            fieldMetadata.setLength(column.getLength());
            fieldMetadata.setScale(column.getScale());
            fieldMetadata.setPrecision(column.getPrecision());
            fieldMetadata.setRequired(!column.isNullable());
            fieldMetadata.setUnique(column.isUnique());
        }
        fieldMetadata.setForeignKeyCollection(false);
    } else {
        fieldMetadata.setForeignKeyCollection(true);
    }
    fieldMetadata.setMutable(true);
    fieldMetadata.setMergedPropertyType(addMetadataFromMappingDataRequest.getMergedPropertyType());
    if (SupportedFieldType.BROADLEAF_ENUMERATION.equals(addMetadataFromMappingDataRequest.getType())) {
        try {
            setupSparkEnumeration(fieldMetadata.getSparkEnumeration(), fieldMetadata,
                    addMetadataFromMappingDataRequest.getDynamicEntityDao());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return FieldProviderResponse.HANDLED;
}

From source file:org.teiid.spring.views.ViewBuilder.java

License:Apache License

@SuppressWarnings("unchecked")
String propertyName(Iterator<org.hibernate.mapping.Property> it,
        org.hibernate.mapping.Property identifierProperty, String colName) {
    if (identifierProperty != null && propertyMatches(identifierProperty, colName)) {
        return identifierProperty.getName();
    }/*from w ww .j a  v  a  2 s . c  o m*/
    while (it.hasNext()) {
        org.hibernate.mapping.Property property = it.next();
        if (propertyMatches(property, colName)) {
            if (property.isComposite()) {
                Component comp = (Component) property.getValue();
                Iterator<org.hibernate.mapping.Property> compIt = comp.getPropertyIterator();
                return propertyName(compIt, null, colName);
            } else {
                return property.getName();
            }
        }
    }
    return null;
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

License:Open Source License

public static void fixSchemaInFormulas(Configuration cfg) {
    cfg.buildMappings();//from  ww  w  .  ja  v a  2s. c  o  m
    String schema = cfg.getProperty("default_schema");
    if (schema != null) {
        for (Iterator i = cfg.getClassMappings(); i.hasNext();) {
            PersistentClass pc = (PersistentClass) i.next();
            for (Iterator j = pc.getPropertyIterator(); j.hasNext();) {
                Property p = (Property) j.next();
                for (Iterator k = p.getColumnIterator(); k.hasNext();) {
                    Selectable c = (Selectable) k.next();
                    if (c instanceof Formula) {
                        Formula f = (Formula) c;
                        if (f.getFormula() != null && f.getFormula().indexOf("%SCHEMA%") >= 0) {
                            f.setFormula(f.getFormula().replaceAll("%SCHEMA%", schema));
                            sLog.debug("Schema updated in " + pc.getClassName() + "." + p.getName() + " to "
                                    + f.getFormula());
                        }
                    }
                }
            }
        }
    }
}

From source file:org.web4thejob.orm.UniqueKeyConstraintImpl.java

License:Open Source License

public PropertyMetadata getPropertyForColumn(Column column) {
    PersistentClass pc = ContextUtil.getBean(HibernateConfiguration.class).getConfiguration()
            .getClassMapping(entityMetadata.getName());

    while (pc != null) {
        for (Iterator<?> iterProps = pc.getPropertyIterator(); iterProps.hasNext();) {
            Property property = (Property) iterProps.next();
            for (Iterator<?> iterCols = property.getColumnIterator(); iterCols.hasNext();) {
                Column col = (Column) iterCols.next();
                if (col.equals(column)) {
                    return entityMetadata.getPropertyMetadata(property.getName());
                }/*from  www  .j ava  2  s .  c om*/
            }
        }

        pc = pc.getSuperclass();
    }

    return null;
}

From source file:org.wintersleep.codeviz.uml.model.HibernateModelFactory.java

License:Apache License

private void addRelations(CodeModel model) throws ClassNotFoundException {
    Iterator<PersistentClass> pci = configuration.getClassMappings();
    while (pci.hasNext()) {
        PersistentClass persistentClass = pci.next();
        final ModelClass mc = model.findModelClass(persistentClass.getMappedClass());
        Iterator<Property> pi = persistentClass.getPropertyIterator();
        while (pi.hasNext()) {
            Property property = pi.next();
            System.out.println(property);
            Value value = property.getValue();
            if (value instanceof ToOne) {
                ToOne toOne = (ToOne) value;
                ModelClass toClass = model.findModelClass(Class.forName(toOne.getReferencedEntityName()));
                RelationEndpoint fromEndpoint = new RelationEndpoint(mc, property.getName());
                fromEndpoint.setMinCardinality(toOne.isNullable() ? 0 : 1);
                RelationEndpoint toEndpoint = new RelationEndpoint(toClass, toOne.getReferencedPropertyName());
                toEndpoint.setMinCardinality(0);
                toEndpoint.setMaxCardinality(RelationEndpoint.MANY_CARDINALITY);
                if (value instanceof OneToOne) {
                    fromEndpoint.setMaxCardinality(1);
                } else if (value instanceof ManyToOne) {
                    fromEndpoint.setMaxCardinality(1);
                }// w  w w. j  a  v  a 2s  . co m
                mc.addRelationTo(fromEndpoint, toEndpoint);
            } else if (value instanceof OneToMany) {
                OneToMany oneToMany = (OneToMany) value;
                oneToMany.getAssociatedClass();
                ModelClass toClass = model.findModelClass(oneToMany.getAssociatedClass().getMappedClass());
                RelationEndpoint fromEndpoint = new RelationEndpoint(mc, property.getName());
                fromEndpoint.setMinCardinality(0);
                fromEndpoint.setMaxCardinality(RelationEndpoint.MANY_CARDINALITY);
                RelationEndpoint toEndpoint = new RelationEndpoint(toClass, "TODO other");
                toEndpoint.setMinCardinality(oneToMany.isNullable() ? 0 : 1);
                toEndpoint.setMaxCardinality(1);
                mc.addRelationTo(fromEndpoint, toEndpoint);
            }
        }
    }
}

From source file:org.zht.framework.service.impl.BaseServiceImpl.java

License:Apache License

private String checkLenth(M m) {
    // final PersistentClass clazz = factory.getConfiguration().getClassMapping(m.getClass().getName()); 
    if (clazz == null) {
        throw new ServiceLogicalException("[]???");
    }//from   w ww.  ja va 2s  .c o m
    // final Table table = clazz.getTable(); 
    //          if(table==null){
    //             throw new ServiceLogicalException("[]???");
    //          }
    @SuppressWarnings("unchecked")
    final Iterator<Property> iterator = clazz.getPropertyIterator();
    if (iterator == null) {
        throw new ServiceLogicalException(
                "[]???");
    }
    // MethodAccess access = MethodAccess.get(m.getClass());
    while (iterator.hasNext()) {
        Property property = iterator.next();
        if ("id".equals(property.getName())) {
            continue;
        }
        Iterator<?> columnIterator = property.getColumnIterator();
        if (columnIterator.hasNext()) {
            Column column = (Column) columnIterator.next();
            int lenth = column.getLength();
            Object value = (Object) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(property.getName()));
            if (value != null) {
                if (value instanceof java.lang.String) {
                    if (lenth < (((java.lang.String) value).length())) {
                        return (" [" + property.getName() + "] ??");
                    }

                }
            }
        }
    }
    return null;
}

From source file:org.zht.framework.service.impl.BaseServiceImpl.java

License:Apache License

private String checkNotNull(M m) {
    // final PersistentClass clazz = factory.getConfiguration().getClassMapping(m.getClass().getName()); 
    if (clazz == null) {
        throw new ServiceLogicalException("[]???");
    }/* w ww . j  a v a2 s  .  c  o m*/
    //final Table table = clazz.getTable(); 
    //          if(table==null){
    //             throw new ServiceLogicalException("[]???");
    //          }
    @SuppressWarnings("unchecked")
    final Iterator<Property> iterator = clazz.getPropertyIterator();
    if (iterator == null) {
        throw new ServiceLogicalException(
                "[]???");
    }
    // MethodAccess access = MethodAccess.get(m.getClass());
    while (iterator.hasNext()) {
        Property property = iterator.next();
        if ("id".equals(property.getName())) {
            continue;
        }
        Iterator<?> columnIterator = property.getColumnIterator();
        if (columnIterator.hasNext()) {
            Column column = (Column) columnIterator.next();
            if (!column.isNullable()) {

                Object value = (Object) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(property.getName()));
                //System.out.println(property.getName()+" "+value);
                if (ZStrUtil.trimToNullIfStr(value) == null) {
                    return (" [" + property.getName() + "] ?");
                }

            }
        }
    }
    return null;
}

From source file:org.zht.framework.service.impl.BaseServiceImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private String checkmanyTone$OneToOneNullForeign(M m) {
    // final PersistentClass clazz = factory.getConfiguration().getClassMapping(m.getClass().getName()); 
    if (clazz == null) {
        throw new ServiceLogicalException("[]???");
    }/*from   w w w.ja v a2s.c o m*/
    final Iterator<Property> iterator = clazz.getPropertyIterator();
    if (iterator == null) {
        throw new ServiceLogicalException(
                "[]???");
    }
    // MethodAccess access = MethodAccess.get(m.getClass());
    while (iterator.hasNext()) {
        Property property = iterator.next();
        if ("id".equals(property.getName())) {
            continue;
        }
        Field field = null;
        try {
            field = m.getClass().getDeclaredField(property.getName());
            if (!(field.isAnnotationPresent(javax.persistence.ManyToOne.class)
                    || field.isAnnotationPresent(javax.persistence.OneToOne.class))) {
                continue;
            }
        } catch (Exception e) {
            continue;
        }
        Iterator<?> columnIterator = property.getColumnIterator();
        if (columnIterator.hasNext()) {
            Column column = (Column) columnIterator.next();
            Object value = (Object) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(property.getName()));
            if (!column.isNullable()) {
                if (ZStrUtil.trimToNullIfStr(value) == null) {
                    return (" [" + property.getName() + "] ?");
                }
                MethodAccess accessZZZ = MethodAccess.get(value.getClass());
                Object foreignModelId = (Object) accessZZZ.invoke(value, "getId");
                if (foreignModelId == null) {
                    return (" [" + property.getName() + "] ?");
                }
            } else {
                if (ZStrUtil.trimToNullIfStr(value) != null) {
                    Object foreignModelId = null;
                    foreignModelId = ZPropertyUtil.getInvokeValue(value, "getId");

                    if (foreignModelId != null && foreignModelId.equals(-972855736L)) {
                        throw new ServiceLogicalException("[]??");
                    }
                    if (foreignModelId == null) {
                        value = null;
                        access.invoke(m, "set" + ZStrUtil.toUpCaseFirst(property.getName()), value);
                    }
                    //                     
                }
                //                  else{
                //                     valueTemp=null;
                //                     access.invoke(m, "set"+ZStrUtil.toUpCaseFirst(property.getName()),valueTemp);
                //                  }
            }
        }
    }
    return null;
}