Example usage for org.hibernate.metadata ClassMetadata getPropertyType

List of usage examples for org.hibernate.metadata ClassMetadata getPropertyType

Introduction

In this page you can find the example usage for org.hibernate.metadata ClassMetadata getPropertyType.

Prototype

Type getPropertyType(String propertyName) throws HibernateException;

Source Link

Document

Get the type of a particular (named) property

Usage

From source file:ar.com.zauber.commons.repository.query.visitor.CriteriaFilterVisitor.java

License:Apache License

/**
 * Obtiene la clase del siguiente pathPart a procesar.
 *
 * @param pathPartClass Clase de un partPath recien procesado
 * @param pathPart siguiente pathPart a procesar
 * @return/*from w  w w.ja  va 2 s . c  om*/
 */
private Class<?> getNextPathPartClass(final Class<?> pathPartClass, final String pathPart) {
    Type hibernateType = null;
    Class<?> nextPathPartClass = null;

    // se obtiene el tipo de hibernate del pathPart actual
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(pathPartClass);
    if (classMetadata != null) { // pathPartClass no es un componente
        hibernateType = classMetadata.getPropertyType(pathPart);
    } else {
        hibernateType = getHibernateTypeFromComponent(pathPart);
    }
    // si es una coleccion se obtiene el tipo del elemento de la coleccion
    if (hibernateType instanceof CollectionType) {
        CollectionType collectionType = (CollectionType) hibernateType;
        hibernateType = sessionFactory.getCollectionMetadata(collectionType.getRole()).getElementType();
    }
    // se resuelve la clase del atributo de busqueda
    // sobre el que se esta actualmente
    if (hibernateType instanceof EntityType) {
        nextPathPartClass = ((EntityType) hibernateType).getReturnedClass();
    } else if (hibernateType instanceof ComponentType) {
        componentType = (ComponentType) hibernateType;
        nextPathPartClass = componentType.getReturnedClass();
    }
    return nextPathPartClass;
}

From source file:ar.com.zauber.commons.repository.query.visitor.CriteriaFilterVisitor.java

License:Apache License

/**
 * Devuelve si el atributo con nombre pathPart de la clase pathPartClass
 * es o no un component.//from  w  ww  .j a v  a2  s . c  o m
 *
 * @param pathPartClass clase que contiene el atributo con nombre pathPart
 * @param pathPart nombre del atributo
 * @return
 */
private boolean isComponentType(final Class<?> pathPartClass, final String pathPart) {
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(pathPartClass);

    // no es un component el contenedor de pathPart
    if (classMetadata != null) {
        return (classMetadata.getPropertyType(pathPart).isComponentType());
    } else { // es un component el contenedor de pathPart
        return (getHibernateTypeFromComponent(pathPart).isComponentType());
    }
}

From source file:com.autobizlogic.abl.data.hibernate.HibPersistentBeanCopy.java

License:Open Source License

/**
 * Create from a state array.//  w ww  .  jav a2s . c o m
 * @param The state (typically from a Hibernate event)
 * @param pk The primary key
 * @param persister The persister for the object
 */
@SuppressWarnings("unchecked")
protected HibPersistentBeanCopy(Object[] state, Object entity, Serializable pk, EntityPersister persister,
        Session session) {
    if (entity instanceof Map)
        map = (Map<String, Object>) entity;
    else {
        bean = entity;
        beanMap = new BeanMap(entity);
    }
    this.pk = pk;
    this.metaEntity = MetaModelFactory.getHibernateMetaModel(persister.getFactory())
            .getMetaEntity(persister.getEntityName());

    ClassMetadata metadata = persister.getClassMetadata();
    String[] propNames = metadata.getPropertyNames();
    for (int i = 0; i < propNames.length; i++) {
        String propName = propNames[i];
        if (metaEntity.getMetaProperty(propName).isCollection())
            continue;

        MetaRole metaRole = metaEntity.getMetaRole(propName);
        if (metaRole == null) { // Not a relationship -- must be an attribute
            if (state[i] != null)
                values.put(propName, state[i]);
        } else if (!metaRole.isCollection()) {
            // In the case of old values, when we are handed the state, it contains the pk for associations,
            // and not (as you'd expect) the object itself. So we check whether the value is a real object,
            // and if it's not, we grab it from the object.
            if (state[i] == null || session.contains(state[i])) {
                values.put(propName, state[i]);
            } else {
                // We have a pk instead of a proxy -- ask Hibernate to create a proxy for it.
                String className = metadata.getPropertyType(propName).getReturnedClass().getName();
                PersistenceContext persContext = HibernateSessionUtil.getPersistenceContextForSession(session);
                EntityPersister entityPersister = HibernateSessionUtil.getEntityPersister(session, className,
                        bean);
                EntityKey entityKey = new EntityKey((Serializable) state[i], entityPersister,
                        session.getEntityMode());

                // Has a proxy already been created for this session?
                Object proxy = persContext.getProxy(entityKey);
                if (proxy == null) {
                    // There is no proxy anywhere for this object, so ask Hibernate to create one for us
                    proxy = entityPersister.createProxy((Serializable) state[i], (SessionImplementor) session);
                    persContext.getBatchFetchQueue().addBatchLoadableEntityKey(entityKey);
                    persContext.addProxy(entityKey, proxy);
                }
                values.put(propName, proxy);
            }
        }
    }
}

From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaEntity.java

License:Open Source License

/**
 * Read all the properties from Hibernate metadata
 *///from w  w  w  .j  av a  2s  . c om
private void loadAllProperties() {
    if (allPropsRetrieved)
        return;

    synchronized (this) {
        if (!allPropsRetrieved) {
            metaAttributes = new HashMap<String, MetaAttribute>();
            metaRoles = new HashMap<String, MetaRole>();
            ClassMetadata meta = persister.getClassMetadata();
            String[] propNames = meta.getPropertyNames();
            for (String propName : propNames) {
                Type type;
                try {
                    type = persister.getClassMetadata().getPropertyType(propName);
                } catch (QueryException ex) {
                    throw new RuntimeException("Unable to determine type for property " + propName
                            + " of entity " + persister.getEntityName());
                }
                if (type.isComponentType()) {
                    // Do nothing
                } else if (type.isCollectionType() || type.isEntityType() || type.isAssociationType()) {
                    boolean isParentToChild = type.isCollectionType();
                    MetaRole mr = new HibMetaRole(this, propName, isParentToChild);
                    metaRoles.put(propName, mr);
                } else {
                    MetaAttribute ma = new HibMetaAttribute(propName, type.getReturnedClass(), false);
                    metaAttributes.put(propName, ma);
                }
            }

            // Often the primary attribute(s) is not returned by ClassMetadata.getPropertyNames
            // So we add it by hand here
            String pkName = meta.getIdentifierPropertyName();

            if (pkName == null) { // Can happen for composite keys
                Type pkType = meta.getIdentifierType();
                if (pkType.isComponentType()) {
                    ComponentType ctype = (ComponentType) pkType;
                    String[] pnames = ctype.getPropertyNames();
                    for (String pname : pnames) {
                        MetaAttribute ma = new HibMetaAttribute(pname,
                                meta.getPropertyType(pname).getReturnedClass(), false);
                        metaAttributes.put(pname, ma);
                    }
                } else
                    throw new RuntimeException(
                            "Unexpected: anonymous PK is not composite - class " + meta.getEntityName());
            } else if (!metaAttributes.containsKey(pkName)) {
                MetaAttribute ma = new HibMetaAttribute(pkName, meta.getIdentifierType().getReturnedClass(),
                        false);
                metaAttributes.put(pkName, ma);
            }

            allPropsRetrieved = true;
        }
    }
}

From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaRole.java

License:Open Source License

/**
 * Get the opposite role of the given role, if it exists
 * @param entityName The name of the entity who owns the role, e.g. com.foo.Customer
 * @param rName The role name, e.g. orders
 * @return Null if the role has no known inverse, or [entity name, role name] of the inverse
 *///from   w w  w .j a v a2s.  c  o  m
private String[] getInverseOfRole(String entityName, String rName) {

    SessionFactory sessFact = ((HibMetaModel) getMetaEntity().getMetaModel()).getSessionFactory();
    ClassMetadata classMeta = sessFact.getClassMetadata(entityName);
    Type propType = classMeta.getPropertyType(rName);
    if (propType.isCollectionType()) {
        return getInverseOfCollectionRole(entityName, rName);
    }

    if (propType.isEntityType()) {
        return getInverseOfSingleRole(entityName, rName);
    }

    log.debug("Role " + entityName + "." + rName + " is neither a collection type "
            + "nor an entity type, and will be assumed to have no inverse.");
    return null;
}

From source file:com.javaetmoi.core.persistence.hibernate.LazyLoadingUtil.java

License:Apache License

@SuppressWarnings("unchecked")
private static void deepInflateEntity(final Session currentSession, Object entity, Set<String> recursiveGuard)
        throws HibernateException {
    if (entity == null) {
        return;//w w  w.jav  a  2  s .  c o m
    }

    Class<? extends Object> persistentClass = entity.getClass();
    if (entity instanceof HibernateProxy) {
        persistentClass = ((HibernateProxy) entity).getHibernateLazyInitializer().getPersistentClass();
    }
    ClassMetadata classMetadata = currentSession.getSessionFactory().getClassMetadata(persistentClass);
    if (classMetadata == null) {
        return;
    }
    Serializable identifier = classMetadata.getIdentifier(entity, (AbstractSessionImpl) currentSession);
    String key = persistentClass.getName() + "|" + identifier;

    if (recursiveGuard.contains(key)) {
        return;
    }
    recursiveGuard.add(key);

    if (!Hibernate.isInitialized(entity)) {
        Hibernate.initialize(entity);
    }

    for (int i = 0, n = classMetadata.getPropertyNames().length; i < n; i++) {
        String propertyName = classMetadata.getPropertyNames()[i];
        Type propertyType = classMetadata.getPropertyType(propertyName);
        Object propertyValue = null;
        if (entity instanceof javassist.util.proxy.ProxyObject) {
            // For javassist proxy, the classMetadata.getPropertyValue(..) method return en
            // emppty collection. So we have to call the property's getter in order to call the
            // JavassistLazyInitializer.invoke(..) method that will initialize the collection by
            // loading it from the database.
            propertyValue = callCollectionGetter(entity, propertyName);
        } else {
            propertyValue = classMetadata.getPropertyValue(entity, propertyName, EntityMode.POJO);
        }
        deepInflateProperty(propertyValue, propertyType, currentSession, recursiveGuard);
    }
}

From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java

License:Open Source License

/**
 * Get Hibernate property type by looking for the property name in the class
 * metadata for general properties and the identifier property
 * //w  w w  .  j a v a 2s .  c om
 * @param cm
 * @param name
 * @return
 */
private org.hibernate.type.Type getPropertyType(ClassMetadata cm, String name) {

    for (String pn : cm.getPropertyNames())
        if (pn.equals(name))
            return cm.getPropertyType(name);

    if (cm.getIdentifierPropertyName() != null && cm.getIdentifierPropertyName().equals(name))
        return cm.getIdentifierType();

    return null;
}

From source file:com.mg.merp.core.support.DatabaseAuditSetupServiceBean.java

License:Open Source License

@PermitAll
public List<PropertyAuditItem> loadPropertyAudit(String entityName) {
    Map<String, PropertyAuditItem> propertyMap = new HashMap<String, PropertyAuditItem>();
    //load metadata from ORM datawarehouse
    ApplicationDictionary ad = ApplicationDictionaryLocator.locate();
    ClassMetadata metadata = ((Session) ServerUtils.getPersistentManager().getDelegate()).getSessionFactory()
            .getClassMetadata(entityName);
    for (String propertyName : metadata.getPropertyNames()) {
        if (!metadata.getPropertyType(propertyName).isCollectionType()) {
            String i18nName = null;
            try {
                Class<?> clazz = ServerUtils.loadClass(entityName);
                if (PersistentObject.class.isAssignableFrom(clazz)) {
                    FieldMetadata fldMetadata = ad.getFieldMetadata(clazz.asSubclass(PersistentObject.class),
                            propertyName);
                    if (fldMetadata != null)
                        i18nName = fldMetadata.getShortLabel();
                }/*from  www.j a v  a  2 s .  c o m*/
            } catch (Exception e) {
                getLogger().error("Load metadata failed", e);
            }
            PropertyAuditItem item = new PropertyAuditItem(i18nName, propertyName, false);
            propertyMap.put(propertyName, item);
        }
    }
    //load setup from database
    List<DatabaseAuditSetup> setupList = findByCriteria(Restrictions.eq("AuditedEntityName", entityName),
            Restrictions.isNotNull("PropertyName"));
    for (DatabaseAuditSetup auditSetup : setupList) {
        PropertyAuditItem item = propertyMap.get(auditSetup.getPropertyName());
        if (item != null) {
            item.setAudit(auditSetup.getAuditModify());//? ??    ?
        } else {
            getLogger().warn(String.format("Entity %s is not contain property %s", entityName,
                    auditSetup.getPropertyName()));
        }
    }
    List<PropertyAuditItem> result = new ArrayList<PropertyAuditItem>(propertyMap.values());
    Collections.sort(result, new Comparator<PropertyAuditItem>() {

        public int compare(PropertyAuditItem o1, PropertyAuditItem o2) {
            return o1.getPropertyName().compareTo(o2.getPropertyName());
        }

    });
    return result;
}

From source file:com.reignite.parser.Join.java

License:Open Source License

/**
 * Gets all the basic fields of the criteria entity
 * //  w w  w .  ja va  2s. c om
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IntrospectionException
 */
public void populateFields()
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, IntrospectionException {
    Class<?> clazz = Class.forName(entity);
    Method getter = clazz.getMethod("get" + Character.toUpperCase(name.charAt(0)) + name.substring(1));

    Class<?> joined = (Class<?>) ((ParameterizedType) getter.getGenericReturnType())
            .getActualTypeArguments()[0];

    ClassMetadata metadata = session.getSessionFactory().getClassMetadata(joined);
    expectedFields.add(name + "." + metadata.getIdentifierPropertyName());
    projections.add(Projections.property(name + "." + metadata.getIdentifierPropertyName()));
    for (String fieldName : metadata.getPropertyNames()) {
        Type type = metadata.getPropertyType(fieldName);
        if (!type.isAnyType() && !type.isAssociationType() && !type.isComponentType()
                && !type.isCollectionType()) {
            String field = name + "." + fieldName;
            expectedFields.add(field);
            projections.add(Projections.property(field));
        }
    }
}

From source file:cz.jirutka.rsql.hibernate.AbstractCriterionBuilder.java

License:Open Source License

/**
 * Find the java type class of given named property in entity's metadata.
 * /*from   ww  w.  j a  v  a 2s.c o  m*/
 * @param property property name
 * @param classMetadata entity metadata
 * @return The java type class of given property.
 * @throws HibernateException If entity does not contain such property.
 */
protected Class<?> findPropertyType(String property, ClassMetadata classMetadata) throws HibernateException {
    return classMetadata.getPropertyType(property).getReturnedClass();
}