Example usage for org.hibernate.type AssociationType getAssociatedEntityName

List of usage examples for org.hibernate.type AssociationType getAssociatedEntityName

Introduction

In this page you can find the example usage for org.hibernate.type AssociationType getAssociatedEntityName.

Prototype

public String getAssociatedEntityName(SessionFactoryImplementor factory) throws MappingException;

Source Link

Document

Get the entity name of the associated entity

Usage

From source file:com.autobizlogic.abl.mgmt.ClassMetadataService.java

License:Open Source License

public static Map<String, Object> getMetadataForClass(Map<String, String> args) {
    String sessionFactoryId = args.get("sessionFactoryId");
    String name = args.get("className");
    HashMap<String, Object> result = new HashMap<String, Object>();

    SessionFactory factory = HibernateConfiguration.getSessionFactoryById(sessionFactoryId);
    if (factory == null)
        return null;

    ClassMetadata meta = factory.getClassMetadata(name);
    if (meta == null)
        return null;

    result.put("sessionFactoryId", sessionFactoryId);
    result.put("className", meta.getEntityName());
    result.put("identifierPropertyName", meta.getIdentifierPropertyName());

    Class<?> cls = meta.getMappedClass(EntityMode.POJO);
    Class<?> supercls = cls.getSuperclass();
    while (ProxyFactory.isProxyClass(supercls))
        supercls = supercls.getSuperclass();
    result.put("superclassName", supercls.getName());

    Map<String, String> properties = new HashMap<String, String>();
    Map<String, Object> collections = new HashMap<String, Object>();
    Map<String, String> associations = new HashMap<String, String>();

    String[] propNames = meta.getPropertyNames();
    Type[] propTypes = meta.getPropertyTypes();
    int i = 0;/*w ww.ja  v a  2  s .c om*/
    for (String propName : propNames) {
        if (propTypes[i].isCollectionType()) {
            CollectionType collType = (CollectionType) propTypes[i];
            Type elementType = collType.getElementType((SessionFactoryImplementor) factory);
            HashMap<String, String> collEntry = new HashMap<String, String>();
            collEntry.put("collectionType", collType.getReturnedClass().getName());
            collEntry.put("elementType", elementType.getName());
            collections.put(propName, collEntry);
        } else if (propTypes[i].isAssociationType()) {
            AssociationType assType = (AssociationType) propTypes[i];
            String assName = assType.getAssociatedEntityName((SessionFactoryImplementor) factory);
            associations.put(propName, assName);
        } else {
            properties.put(propName, propTypes[i].getName());
        }
        i++;
    }
    result.put("properties", properties);
    result.put("associations", associations);
    result.put("collections", collections);

    MetaModel metaModel = MetaModelFactory.getHibernateMetaModel(factory);
    LogicGroup logicGroup = RuleManager.getInstance(metaModel).getLogicGroupForClassName(name);
    if (logicGroup != null) {

        // Operations are actually actions and constraints
        List<Map<String, Object>> operations = new Vector<Map<String, Object>>();
        result.put("operations", operations);

        Set<ActionRule> actions = logicGroup.getActions();
        if (actions != null && actions.size() > 0) {
            for (ActionRule a : actions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "action");
                operations.add(op);
            }
        }

        Set<EarlyActionRule> eactions = logicGroup.getEarlyActions();
        if (eactions != null && eactions.size() > 0) {
            for (EarlyActionRule a : eactions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "early action");
                operations.add(op);
            }
        }

        Set<CommitActionRule> cactions = logicGroup.getCommitActions();
        if (cactions != null && cactions.size() > 0) {
            for (CommitActionRule a : cactions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "commit action");
                operations.add(op);
            }
        }

        Set<ConstraintRule> constraints = logicGroup.getConstraints();
        if (constraints != null && constraints.size() > 0) {
            for (ConstraintRule constraint : constraints) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", constraint.getLogicMethodName());
                op.put("type", "constraint");
                operations.add(op);
            }
        }

        Set<CommitConstraintRule> cconstraints = logicGroup.getCommitConstraints();
        if (cconstraints != null && cconstraints.size() > 0) {
            for (ConstraintRule cconstraint : cconstraints) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", cconstraint.getLogicMethodName());
                op.put("type", "commit constraint");
                operations.add(op);
            }
        }

        // Derivations are derived attributes
        Map<String, Object> derivations = new HashMap<String, Object>();
        result.put("derivations", derivations);

        Set<AbstractAggregateRule> aggregates = logicGroup.getAggregates();
        if (aggregates != null && aggregates.size() > 0) {
            for (AbstractAggregateRule aggregate : aggregates) {
                Map<String, Object> agg = new HashMap<String, Object>();
                if (aggregate instanceof CountRule)
                    agg.put("type", "count");
                else if (aggregate instanceof SumRule)
                    agg.put("type", "sum");
                else
                    agg.put("type", "unknown");
                agg.put("methodName", aggregate.getLogicMethodName());
                derivations.put(aggregate.getBeanAttributeName(), agg);
            }
        }

        List<FormulaRule> formulas = logicGroup.getFormulas();
        if (formulas != null && formulas.size() > 0) {
            for (FormulaRule formula : formulas) {
                Map<String, Object> form = new HashMap<String, Object>();
                form.put("type", "formula");
                form.put("methodName", formula.getLogicMethodName());
                derivations.put(formula.getBeanAttributeName(), form);
            }
        }

        Set<ParentCopyRule> pcRules = logicGroup.getParentCopies();
        if (pcRules != null && pcRules.size() > 0) {
            for (ParentCopyRule pcRule : pcRules) {
                Map<String, Object> parentCopy = new HashMap<String, Object>();
                parentCopy.put("type", "parent copy");
                parentCopy.put("methodName", pcRule.getLogicMethodName());
                derivations.put(pcRule.getChildAttributeName(), parentCopy);
            }
        }
    }

    HashMap<String, Object> finalResult = new HashMap<String, Object>();
    finalResult.put("data", result);

    return finalResult;
}

From source file:com.wavemaker.runtime.data.util.DataServiceUtils.java

License:Open Source License

public static String getJavaTypeName(Type type, SessionFactory factory) {
    if (type.isCollectionType()) {
        AssociationType ass = (AssociationType) type;
        SessionFactoryImplementor fai = (SessionFactoryImplementor) factory;
        return ass.getAssociatedEntityName(fai);
    } else {//from ww w  . j  a  va 2s.c  o  m
        return type.getReturnedClass().getName();
    }
}

From source file:cz.jirutka.rsql.visitor.hibernate.HibernateCriterionVisitor.java

License:Apache License

private Tuple<Type, String>[] getPath(ClassMetadata classMetadata, String[] names) {
    Tuple<Type, String>[] path = new Tuple[names.length];
    Object element = classMetadata;
    for (int i = 0; i < names.length; ++i) {
        String name = names[i];//w  w  w  .  jav  a2  s .co m
        Type propertyType = getPropertyType(element, name);
        path[i] = new Tuple<Type, String>(propertyType, name);
        if (propertyType.isCollectionType()) {
            CollectionType collectionType = (CollectionType) propertyType;
            String associatedEntityName = collectionType.getRole();
            CollectionPersister collectionPersister = getSessionFactory()
                    .getCollectionPersister(associatedEntityName);
            element = collectionPersister.getElementType();
        } else if (propertyType.isAssociationType()) {
            AssociationType associationType = (AssociationType) propertyType;
            String associatedEntityName = associationType.getAssociatedEntityName(getSessionFactory());
            element = getSessionFactory().getClassMetadata(associatedEntityName);
        } else if (propertyType.isComponentType()) {
            element = propertyType;
        }
    }
    return path;
}

From source file:gov.nih.nci.security.upt.util.HibernateHelper.java

License:BSD License

public static HashMap getAssociatedClasses(String className) throws CSException {
    System.out.println("className " + className);
    boolean isParentClass = false;
    HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession();
    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        throw new CSException("Session Expired - Please Relogin!");
    }/*from  w w w .jav  a2 s  .c  om*/

    if (className.contains(" - self")) {
        throw new CSException("No Associations allowed for direct security filter clause.");
    }

    SessionFactory sessionFactory = (SessionFactory) session
            .getAttribute(DisplayConstants.HIBERNATE_SESSIONFACTORY);
    HashMap map = new HashMap();
    if (!(className.contains(" - "))) {
        isParentClass = true;
    } else {
        className = className.substring(0, className.indexOf(" - "));
    }
    System.out.println("className2 " + className);
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(className);
    String[] properties = classMetadata.getPropertyNames();
    for (int i = 0; i < properties.length; i++) {
        Type type = classMetadata.getPropertyType(properties[i]);
        if (type instanceof AssociationType) {
            try {
                AssociationType associationType = (AssociationType) type;
                map.put(properties[i],
                        associationType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory)
                                + " - " + properties[i]);
            } catch (Exception e) {
                throw new CSException("Hibernate Error: " + e.getMessage());
            }
        }
    }
    System.out.println("isParentClass " + isParentClass);
    if (isParentClass) {
        map.put(className, className + " - self");
    }
    if (map.size() == 0)
        throw new CSException("No associated Classes Found!");
    System.out.println("map " + map);
    return map;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateDomainClass.java

License:Apache License

/**
 * Contructor to be used by all child classes to create a new instance
 * and get the name right.// w w w  . java2 s  .com
 *
 * @param clazz          the Grails class
 * @param sessionFactory The Hibernate SessionFactory instance
 * @param metaData       The ClassMetaData for this class retrieved from the SF
 */
public GrailsHibernateDomainClass(Class<?> clazz, SessionFactory sessionFactory, GrailsApplication application,
        ClassMetadata metaData) {
    super(clazz, "");
    this.application = application;

    new StandardAnnotationMetadata(clazz);
    String ident = metaData.getIdentifierPropertyName();
    if (ident != null) {
        Class<?> identType = getPropertyType(ident);
        identifier = new GrailsHibernateDomainClassProperty(this, ident);
        identifier.setIdentity(true);
        identifier.setType(identType);
        propertyMap.put(ident, identifier);
    }

    // configure the version property
    final int versionIndex = metaData.getVersionProperty();
    String versionPropertyName = null;
    if (versionIndex > -1) {
        versionPropertyName = metaData.getPropertyNames()[versionIndex];
        version = new GrailsHibernateDomainClassProperty(this, versionPropertyName);
        version.setType(getPropertyType(versionPropertyName));
    }

    // configure remaining properties
    String[] propertyNames = metaData.getPropertyNames();
    for (String propertyName : propertyNames) {
        if (!propertyName.equals(ident)
                && !(versionPropertyName != null && propertyName.equals(versionPropertyName))) {
            GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this,
                    propertyName);
            prop.setType(getPropertyType(propertyName));
            Type hibernateType = metaData.getPropertyType(propertyName);

            // if its an association type
            if (hibernateType.isAssociationType()) {
                prop.setAssociation(true);
                // get the associated type from the session factory and set it on the property
                AssociationType assType = (AssociationType) hibernateType;
                if (assType instanceof AnyType) {
                    continue;
                }
                try {
                    String associatedEntity = assType
                            .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
                    ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity);
                    prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO));
                } catch (MappingException me) {
                    // other side must be a value object
                    if (hibernateType.isCollectionType()) {
                        prop.setRelatedClassType(Collection.class);
                    }
                }
                // configure type of relationship
                if (hibernateType.isCollectionType()) {
                    prop.setOneToMany(true);
                } else if (hibernateType.isEntityType()) {
                    prop.setManyToOne(true);
                    // might not really be true, but for our purposes this is ok
                    prop.setOneToOne(true);
                }
            }
            propertyMap.put(propertyName, prop);
        }
    }

    properties = propertyMap.values().toArray(new GrailsDomainClassProperty[propertyMap.size()]);
    // process the constraints
    evaluateConstraints();
}

From source file:org.grails.orm.hibernate.GrailsHibernateDomainClass.java

License:Apache License

protected void setRelatedClassType(GrailsHibernateDomainClassProperty prop, AssociationType assType,
        Type hibernateType) {// w  w  w .j  av  a2s  .co  m
    try {
        String associatedEntity = assType
                .getAssociatedEntityName((SessionFactoryImplementor) getSessionFactory());
        ClassMetadata associatedMetaData = getSessionFactory().getClassMetadata(associatedEntity);
        prop.setRelatedClassType(associatedMetaData.getMappedClass());
    } catch (MappingException me) {
        // other side must be a value object
        if (hibernateType.isCollectionType()) {
            prop.setRelatedClassType(Collection.class);
        }
    }
}

From source file:org.nextframework.persistence.PersistenceUtils.java

License:Apache License

public static Class<?> getPropertyAssociationType(SessionFactory sessionFactory, Class<?> clazz,
        String property) {//from ww  w  .j a v  a2s .c o  m
    Class<?> result = null;
    ClassMetadata classMetadata = getClassMetadata(clazz, sessionFactory);
    if (classMetadata == null) {
        throw new PersistenceException("Class " + clazz.getName() + " is not mapped. ");
    }
    org.hibernate.type.Type propertyType = classMetadata.getPropertyType(property);
    if (propertyType instanceof AssociationType) {
        AssociationType associationType = (AssociationType) propertyType;
        String associatedEntityName = associationType
                .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
        AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) sessionFactory
                .getClassMetadata(associatedEntityName);
        result = abstractEntityPersister.getEntityType().getReturnedClass();
    } else {
        throw new PersistenceException("Property \"" + property + "\" of " + clazz
                + " is not an association type (i.e. ManyToOne, OneToMany, AnyType, etc)");
    }
    return result;
}