Example usage for org.hibernate.mapping OneToMany getReferencedEntityName

List of usage examples for org.hibernate.mapping OneToMany getReferencedEntityName

Introduction

In this page you can find the example usage for org.hibernate.mapping OneToMany getReferencedEntityName.

Prototype

public String getReferencedEntityName() 

Source Link

Usage

From source file:gov.nih.nci.system.util.ClassCache.java

License:BSD License

@SuppressWarnings("unchecked")
private Map<String, List<Object>> processIfAssociationType(Property property, String fieldName,
        Configuration cfg) {//from   www. j  a  va  2 s  . c  om
    Map<String, List<Object>> associationPsFields = new HashMap<String, List<Object>>();

    org.hibernate.mapping.Set childAssociationType = (org.hibernate.mapping.Set) property.getValue();
    Object element = childAssociationType.getElement();
    Class<? extends Value> elementClass = childAssociationType.getElement().getClass();
    if (Component.class.isAssignableFrom(elementClass)) {
        Component associationComponent = (Component) element;
        Iterator<Property> propertiesIterator = associationComponent.getPropertyIterator();
        String assoChildCompClassName = associationComponent.getComponentClassName();
        String key = fieldName + "<" + assoChildCompClassName + ">";
        List<Object> isoPersistentFields = new ArrayList<Object>();
        while (propertiesIterator.hasNext()) {
            Property tempProperty = propertiesIterator.next();
            List<Object> tempPersistentFields = getPersistentFieldsForISOObject(tempProperty);
            Class<? extends Value> tempPropertyClass = tempProperty.getValue().getClass();
            if (Component.class.isAssignableFrom(tempPropertyClass)) {
                Map<String, List<Object>> nestedComponent = new HashMap<String, List<Object>>();
                nestedComponent.put(tempProperty.getName(), tempPersistentFields);
                isoPersistentFields.add(nestedComponent);
            } else {
                isoPersistentFields.addAll(tempPersistentFields);
            }
        }
        associationPsFields.put(key, isoPersistentFields);
    } else if (element instanceof ManyToOne) {
        ManyToOne manyToOne = (ManyToOne) childAssociationType.getElement();
        String many2OnePClassName = manyToOne.getReferencedEntityName();
        if (!many2OnePClassName.startsWith("_xxEntityxx_gov_nih_nci_cacoresdk_domain_other_datatype")) {
            return associationPsFields;
        }
        PersistentClass many2OnePClass = cfg.getClassMapping(many2OnePClassName);
        Map<String, List<Object>> map = getISOPropertiesForObject(many2OnePClass, cfg);
        Iterator<String> keyItr = map.keySet().iterator();

        String key = fieldName + "<" + many2OnePClass.getClassName() + ">";
        List<Object> isoPersistentFields = new ArrayList<Object>();
        isoPersistentFields.add(map);
        associationPsFields.put(key, isoPersistentFields);
    } else if (element instanceof OneToMany) {
        OneToMany oneToMany = (OneToMany) element;//prop.getValue();
        String oneToManyPClassName = oneToMany.getReferencedEntityName();
        if (!oneToManyPClassName.startsWith("_xxEntityxx_gov_nih_nci_cacoresdk_domain_other_datatype")) {
            return associationPsFields;
        }
        PersistentClass oneToManyPClass = cfg.getClassMapping(oneToManyPClassName);
        Map<String, List<Object>> map = getISOPropertiesForObject(oneToManyPClass, cfg);
        Iterator<String> keyItr = map.keySet().iterator();

        String key = fieldName + "<" + oneToMany.getAssociatedClass().getClassName() + ">";
        List<Object> isoPersistentFields = new ArrayList<Object>();
        isoPersistentFields.add(map);
        associationPsFields.put(key, isoPersistentFields);
    } else {
        log.info("ignoring :::" + elementClass.getName());
    }
    return associationPsFields;
}

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

License:Apache License

protected void bindCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings,
        Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) {

    PersistentClass associatedClass = null;

    if (LOG.isDebugEnabled())
        LOG.debug("Mapping collection: " + collection.getRole() + " -> "
                + collection.getCollectionTable().getName());

    PropertyConfig propConfig = getPropertyConfig(property);

    if (propConfig != null && StringUtils.hasText(propConfig.getSort())) {
        if (!property.isBidirectional() && property.isOneToMany()) {
            throw new GrailsDomainException("Default sort for associations ["
                    + property.getDomainClass().getName() + "->" + property.getName()
                    + "] are not supported with unidirectional one to many relationships.");
        }/*from   w w  w.jav a  2 s . c o  m*/
        GrailsDomainClass referenced = property.getReferencedDomainClass();
        if (referenced != null) {
            GrailsDomainClassProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());

            String associatedClassName = property.getReferencedDomainClass().getFullName();

            associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
            if (associatedClass != null) {
                collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass,
                        collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
            }
        }
    }

    // Configure one-to-many
    if (collection.isOneToMany()) {

        GrailsDomainClass referenced = property.getReferencedDomainClass();
        Mapping m = getRootMapping(referenced);
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();

        if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
            Mapping rootMapping = getRootMapping(referenced);
            String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;

            if (rootMapping != null) {
                final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn();
                if (discriminatorColumn != null) {
                    discriminatorColumnName = discriminatorColumn.getName();
                }
                if (rootMapping.getDiscriminatorMap().get("formula") != null) {
                    discriminatorColumnName = (String) m.getDiscriminatorMap().get("formula");
                }
            }
            //NOTE: this will build the set for the in clause if it has sublcasses
            Set<String> discSet = buildDiscriminatorSet(referenced);
            String inclause = DefaultGroovyMethods.join(discSet, ",");

            collection.setWhere(discriminatorColumnName + " in (" + inclause + ")");
        }

        OneToMany oneToMany = (OneToMany) collection.getElement();
        String associatedClassName = oneToMany.getReferencedEntityName();

        associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
        // if there is no persistent class for the association throw exception
        if (associatedClass == null) {
            throw new MappingException(
                    "Association references unmapped class: " + oneToMany.getReferencedEntityName());
        }

        oneToMany.setAssociatedClass(associatedClass);
        if (shouldBindCollectionWithForeignKey(property)) {
            collection.setCollectionTable(associatedClass.getTable());
        }

        bindCollectionForPropertyConfig(collection, propConfig);
    }

    if (isSorted(property)) {
        collection.setSorted(true);
    }

    // setup the primary key references
    DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses);

    // link a bidirectional relationship
    if (property.isBidirectional()) {
        GrailsDomainClassProperty otherSide = property.getOtherSide();
        if (otherSide.isManyToOne() && shouldBindCollectionWithForeignKey(property)) {
            linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
        } else if (property.isManyToMany() || Map.class.isAssignableFrom(property.getType())) {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    } else {
        if (hasJoinKeyMapping(propConfig)) {
            bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings);
        } else {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    }
    collection.setKey(key);

    // get cache config
    if (propConfig != null) {
        CacheConfig cacheConfig = propConfig.getCache();
        if (cacheConfig != null) {
            collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
        }
    }

    // if we have a many-to-many
    if (property.isManyToMany() || isBidirectionalOneToManyMap(property)) {
        GrailsDomainClassProperty otherSide = property.getOtherSide();

        if (property.isBidirectional()) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getDomainClass().getName()
                        + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName()
                        + " as ManyToOne");
            ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable());
            bindManyToMany(otherSide, element, mappings, sessionFactoryBeanName);
            collection.setElement(element);
            bindCollectionForPropertyConfig(collection, propConfig);
            if (property.isCircular()) {
                collection.setInverse(false);
            }
        } else {
            // TODO support unidirectional many-to-many
        }
    } else if (shouldCollectionBindWithJoinColumn(property)) {
        bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName);

    } else if (isUnidirectionalOneToMany(property)) {
        // for non-inverse one-to-many, with a not-null fk, add a backref!
        // there are problems with list and map mappings and join columns relating to duplicate key constraints
        // TODO change this when HHH-1268 is resolved
        bindUnidirectionalOneToMany(property, mappings, collection);
    }
}

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

License:Apache License

private static void bindCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings,
        Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) {

    PersistentClass associatedClass = null;

    if (LOG.isDebugEnabled())
        LOG.debug("Mapping collection: " + collection.getRole() + " -> "
                + collection.getCollectionTable().getName());

    PropertyConfig propConfig = getPropertyConfig(property);

    if (propConfig != null && !StringUtils.isBlank(propConfig.getSort())) {
        if (!property.isBidirectional() && property.isOneToMany()) {
            throw new GrailsDomainException("Default sort for associations ["
                    + property.getDomainClass().getName() + "->" + property.getName()
                    + "] are not supported with unidirectional one to many relationships.");
        }//from   www .j a  v  a 2s.c  o m
        GrailsDomainClass referenced = property.getReferencedDomainClass();
        if (referenced != null) {
            GrailsDomainClassProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());

            String associatedClassName = property.getReferencedDomainClass().getFullName();

            associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
            if (associatedClass != null) {
                collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass,
                        collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
            }
        }
    }

    // Configure one-to-many
    if (collection.isOneToMany()) {

        GrailsDomainClass referenced = property.getReferencedDomainClass();
        Mapping m = getRootMapping(referenced);
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();

        if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
            Mapping rootMapping = getRootMapping(referenced);
            String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;

            if (rootMapping != null) {
                final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn();
                if (discriminatorColumn != null) {
                    discriminatorColumnName = discriminatorColumn.getName();
                }
                if (rootMapping.getDiscriminatorMap().get("formula") != null) {
                    discriminatorColumnName = (String) m.getDiscriminatorMap().get("formula");
                }
            }
            //NOTE: this will build the set for the in clause if it has sublcasses
            Set<String> discSet = buildDiscriminatorSet(referenced);
            String inclause = StringUtils.join(discSet, ',');

            collection.setWhere(discriminatorColumnName + " in (" + inclause + ")");
        }

        OneToMany oneToMany = (OneToMany) collection.getElement();
        String associatedClassName = oneToMany.getReferencedEntityName();

        associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
        // if there is no persistent class for the association throw exception
        if (associatedClass == null) {
            throw new MappingException(
                    "Association references unmapped class: " + oneToMany.getReferencedEntityName());
        }

        oneToMany.setAssociatedClass(associatedClass);
        if (shouldBindCollectionWithForeignKey(property)) {
            collection.setCollectionTable(associatedClass.getTable());
        }

        bindCollectionForPropertyConfig(collection, propConfig);
    }

    if (isSorted(property)) {
        collection.setSorted(true);
    }

    // setup the primary key references
    DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses);

    // link a bidirectional relationship
    if (property.isBidirectional()) {
        GrailsDomainClassProperty otherSide = property.getOtherSide();
        if (otherSide.isManyToOne() && shouldBindCollectionWithForeignKey(property)) {
            linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
        } else if (property.isManyToMany() || Map.class.isAssignableFrom(property.getType())) {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    } else {
        if (hasJoinKeyMapping(propConfig)) {
            bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings);
        } else {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    }
    collection.setKey(key);

    // get cache config
    if (propConfig != null) {
        CacheConfig cacheConfig = propConfig.getCache();
        if (cacheConfig != null) {
            collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
        }
    }

    // if we have a many-to-many
    if (property.isManyToMany() || isBidirectionalOneToManyMap(property)) {
        GrailsDomainClassProperty otherSide = property.getOtherSide();

        if (property.isBidirectional()) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getDomainClass().getName()
                        + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName()
                        + " as ManyToOne");
            ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable());
            bindManyToMany(otherSide, element, mappings, sessionFactoryBeanName);
            collection.setElement(element);
            bindCollectionForPropertyConfig(collection, propConfig);
            if (property.isCircular()) {
                collection.setInverse(false);
            }
        } else {
            // TODO support unidirectional many-to-many
        }
    } else if (shouldCollectionBindWithJoinColumn(property)) {
        bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName);

    } else if (isUnidirectionalOneToMany(property)) {
        // for non-inverse one-to-many, with a not-null fk, add a backref!
        // there are problems with list and map mappings and join columns relating to duplicate key constraints
        // TODO change this when HHH-1268 is resolved
        bindUnidirectionalOneToMany(property, mappings, collection);
    }
}

From source file:org.eclipse.emf.teneo.hibernate.HbDataStore.java

License:Open Source License

/**
 * Computes the referers, handles the lazy for containment
 *///  w  w  w .j  ava2 s.  c  o m
protected HashMap<String, java.util.List<ReferenceTo>> computeReferers() {
    final HashMap<String, java.util.List<ReferenceTo>> result = new HashMap<String, java.util.List<ReferenceTo>>();

    final Iterator<?> it = getClassMappings();
    final ArrayList<String> fmes = new ArrayList<String>();
    while (it.hasNext()) {
        final PersistentClass pc = (PersistentClass) it.next();

        // keep track which are the feature map entries
        if (pc.getMetaAttribute(HbMapperConstants.FEATUREMAP_META) != null) {
            fmes.add(getMappedName(pc));
        }

        // everyone should have a list otherwise the copying of referers to
        // super types to
        // this type does not work
        if (result.get(getMappedName(pc)) == null) {
            result.put(getMappedName(pc), new ArrayList<ReferenceTo>());
        }

        final Iterator<?> propIt = pc.getPropertyIterator();
        while (propIt.hasNext()) {
            // handle few cases
            // OneToOne or ManyToOne, referenced class can be obtained from
            // Value and then getReferencedEntityName
            // List: in this case search for a structural feature and get
            // the EType from it
            // if no structural feature then use the type name and hope for
            // the best.

            final Property prop = (Property) propIt.next();
            EClass eClass = null;
            if (pc.getMetaAttribute(HbMapperConstants.FEATUREMAP_META) == null) {
                if (pc.getEntityName() != null) {
                    eClass = getEntityNameStrategy().toEClass(pc.getEntityName());
                } else {
                    eClass = EModelResolver.instance().getEClass(pc.getMappedClass());
                }
            }

            final EStructuralFeature ef = eClass == null ? null
                    : StoreUtil.getEStructuralFeature(eClass, prop.getName());
            try {
                String toEntity = "";
                boolean isContainer = false;
                boolean isMany = false;

                if (prop.getValue() instanceof ManyToOne) {
                    final ManyToOne mto = (ManyToOne) prop.getValue();
                    toEntity = mto.getReferencedEntityName();
                    if (ef != null) {
                        isContainer = ef instanceof EReference && ((EReference) ef).isContainment();
                    } else {
                        isContainer = prop.getCascadeStyle().hasOrphanDelete()
                                || prop.getCascade().compareTo("all") == 0; // ugly
                        // but
                    }
                    // this was
                    // the only
                    // way to
                    // get all
                    // there!
                } else if (prop.getValue() instanceof OneToOne) {
                    final OneToOne oto = (OneToOne) prop.getValue();
                    toEntity = oto.getReferencedEntityName();
                    if (ef != null) {
                        isContainer = ef instanceof EReference && ((EReference) ef).isContainment();
                    } else {
                        isContainer = prop.getCascadeStyle().hasOrphanDelete()
                                || prop.getCascadeStyle() == CascadeStyle.ALL;
                    }
                } else if (prop.getValue() instanceof Collection) {
                    isMany = true;
                    if (ef == null) { // TODO can this happen?
                        isContainer = prop.getCascadeStyle().hasOrphanDelete()
                                || prop.getCascadeStyle() == CascadeStyle.ALL;
                        if (((Collection) prop.getValue()).getElement() instanceof OneToMany) {
                            final Collection coll = (Collection) prop.getValue();
                            toEntity = ((OneToMany) coll.getElement()).getReferencedEntityName();
                        } else if (((Collection) prop.getValue()).getElement() instanceof ManyToOne) {
                            final Collection coll = (Collection) prop.getValue();
                            toEntity = ((ManyToOne) coll.getElement()).getReferencedEntityName();
                        } else {
                            continue;
                            // throw new HbMapperException("Type "
                            // + ((Collection)
                            // prop.getValue()).getElement().getClass().getName()
                            // + " not supported, property " +
                            // prop.getName());
                        }
                    } else {
                        // in case of featuremap set containment always on
                        // true because only the featuremap entries
                        // themselves know if they are containment
                        if (ef instanceof EAttribute
                                && ((EAttribute) ef).getEType().getInstanceClass() == Entry.class) {
                            isContainer = true;
                            // composite-elements are not supported.
                            if (!(((Collection) prop.getValue()).getElement() instanceof OneToMany)) {
                                continue;
                            }
                            final OneToMany otm = (OneToMany) ((Collection) prop.getValue()).getElement();
                            toEntity = otm.getReferencedEntityName();
                        } else if (ef instanceof EReference) {
                            final EReference er = (EReference) ef;
                            isContainer = er.isContainment(); // prop.getCascadeStyle().
                            // hasOrphanDelete()
                            // ||
                            // prop.getCascadeStyle()
                            // ==
                            // CascadeStyle.ALL;
                            toEntity = getEntityNameStrategy()
                                    .toEntityName(((EReference) ef).getEReferenceType());
                        } else if (ef instanceof EAttribute && ef.getEType() instanceof EClass) { // TODO
                            // can
                            // this
                            // ever
                            // happen?
                            isContainer = true; // prop.getCascadeStyle().hasOrphanDelete()
                            // || prop.getCascadeStyle()
                            // == CascadeStyle.ALL;
                            toEntity = getEntityNameStrategy().toEntityName((EClass) ef.getEType());
                        }
                        // filter out non eobjects
                        else {
                            continue;
                        }
                    }
                } else {
                    continue;
                }

                java.util.List<ReferenceTo> list = result.get(toEntity);
                if (list == null) {
                    list = new ArrayList<ReferenceTo>();
                    result.put(toEntity, list);
                }

                list.add(new ReferenceTo(getMappedName(pc), prop, isContainer, isMany, toEntity));
            } catch (StoreClassLoadException e) {
                throw new HbMapperException("Class not found using property: " + prop.getName() + " of " + prop,
                        e);
            }
        }
    }

    // at the end for each class all the refersto of superclasses and
    // interfaces are added also
    final ArrayList<EClass> classDone = new ArrayList<EClass>();
    for (String em : result.keySet()) {
        // only do this if not a fme
        if (!fmes.contains(em)) {
            setRefersToOfSupers(em, result, classDone);
        }
    }
    return result;
}

From source file:org.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java

License:Apache License

protected void bindCollectionSecondPass(ToMany property, Mappings mappings, Map<?, ?> persistentClasses,
        Collection collection, String sessionFactoryBeanName) {

    PersistentClass associatedClass = null;

    if (LOG.isDebugEnabled())
        LOG.debug("Mapping collection: " + collection.getRole() + " -> "
                + collection.getCollectionTable().getName());

    PropertyConfig propConfig = getPropertyConfig(property);

    if (propConfig != null && StringUtils.hasText(propConfig.getSort())) {
        if (!property.isBidirectional()
                && (property instanceof org.grails.datastore.mapping.model.types.OneToMany)) {
            throw new DatastoreConfigurationException("Default sort for associations ["
                    + property.getOwner().getName() + "->" + property.getName()
                    + "] are not supported with unidirectional one to many relationships.");
        }//from  w  ww. j  a v a 2  s.  c  om
        PersistentEntity referenced = property.getAssociatedEntity();
        if (referenced != null) {
            PersistentProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());

            String associatedClassName = property.getAssociatedEntity().getName();

            associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
            if (associatedClass != null) {
                collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass,
                        collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
            }
        }
    }

    // Configure one-to-many
    if (collection.isOneToMany()) {

        PersistentEntity referenced = property.getAssociatedEntity();
        Mapping m = getRootMapping(referenced);
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();

        if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
            Mapping rootMapping = getRootMapping(referenced);
            String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;

            if (rootMapping != null) {
                final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn();
                if (discriminatorColumn != null) {
                    discriminatorColumnName = discriminatorColumn.getName();
                }
                if (rootMapping.getDiscriminatorMap().get("formula") != null) {
                    discriminatorColumnName = (String) m.getDiscriminatorMap().get("formula");
                }
            }
            //NOTE: this will build the set for the in clause if it has sublcasses
            Set<String> discSet = buildDiscriminatorSet((HibernatePersistentEntity) referenced);
            String inclause = DefaultGroovyMethods.join(discSet, ",");

            collection.setWhere(discriminatorColumnName + " in (" + inclause + ")");
        }

        OneToMany oneToMany = (OneToMany) collection.getElement();
        String associatedClassName = oneToMany.getReferencedEntityName();

        associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
        // if there is no persistent class for the association throw exception
        if (associatedClass == null) {
            throw new MappingException(
                    "Association references unmapped class: " + oneToMany.getReferencedEntityName());
        }

        oneToMany.setAssociatedClass(associatedClass);
        if (shouldBindCollectionWithForeignKey(property)) {
            collection.setCollectionTable(associatedClass.getTable());
        }

        bindCollectionForPropertyConfig(collection, propConfig);
    }

    if (isSorted(property)) {
        collection.setSorted(true);
    }

    // setup the primary key references
    DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses);

    // link a bidirectional relationship
    if (property.isBidirectional()) {
        Association otherSide = property.getInverseSide();
        if ((otherSide instanceof org.grails.datastore.mapping.model.types.ToOne)
                && shouldBindCollectionWithForeignKey(property)) {
            linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
        } else if ((otherSide instanceof ManyToMany) || Map.class.isAssignableFrom(property.getType())) {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    } else {
        if (hasJoinKeyMapping(propConfig)) {
            bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings);
        } else {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    }
    collection.setKey(key);

    // get cache config
    if (propConfig != null) {
        CacheConfig cacheConfig = propConfig.getCache();
        if (cacheConfig != null) {
            collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
        }
    }

    // if we have a many-to-many
    final boolean isManyToMany = property instanceof ManyToMany;
    if (isManyToMany || isBidirectionalOneToManyMap(property)) {
        PersistentProperty otherSide = property.getInverseSide();

        if (property.isBidirectional()) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getOwner().getName() + "."
                        + otherSide.getName() + " -> " + collection.getCollectionTable().getName()
                        + " as ManyToOne");
            ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable());
            bindManyToMany((Association) otherSide, element, mappings, sessionFactoryBeanName);
            collection.setElement(element);
            bindCollectionForPropertyConfig(collection, propConfig);
            if (property.isCircular()) {
                collection.setInverse(false);
            }
        } else {
            // TODO support unidirectional many-to-many
        }
    } else if (shouldCollectionBindWithJoinColumn(property)) {
        bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName);

    } else if (isUnidirectionalOneToMany(property)) {
        // for non-inverse one-to-many, with a not-null fk, add a backref!
        // there are problems with list and map mappings and join columns relating to duplicate key constraints
        // TODO change this when HHH-1268 is resolved
        bindUnidirectionalOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, mappings,
                collection);
    }
}

From source file:org.grails.orm.hibernate.cfg.GrailsDomainBinder.java

License:Apache License

protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollector mappings,
        Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) {

    PersistentClass associatedClass = null;

    if (LOG.isDebugEnabled())
        LOG.debug("Mapping collection: " + collection.getRole() + " -> "
                + collection.getCollectionTable().getName());

    PropertyConfig propConfig = getPropertyConfig(property);

    PersistentEntity referenced = property.getAssociatedEntity();
    if (propConfig != null && StringUtils.hasText(propConfig.getSort())) {
        if (!property.isBidirectional()
                && (property instanceof org.grails.datastore.mapping.model.types.OneToMany)) {
            throw new DatastoreConfigurationException("Default sort for associations ["
                    + property.getOwner().getName() + "->" + property.getName()
                    + "] are not supported with unidirectional one to many relationships.");
        }/*from  w w  w.jav a  2  s  .co  m*/
        if (referenced != null) {
            PersistentProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());

            String associatedClassName = property.getAssociatedEntity().getName();

            associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
            if (associatedClass != null) {
                collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass,
                        collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
            }
        }
    }

    // Configure one-to-many
    if (collection.isOneToMany()) {

        Mapping m = getRootMapping(referenced);
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();

        if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
            Mapping rootMapping = getRootMapping(referenced);
            String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;

            if (rootMapping != null) {
                DiscriminatorConfig discriminatorConfig = rootMapping.getDiscriminator();
                if (discriminatorConfig != null) {
                    final ColumnConfig discriminatorColumn = discriminatorConfig.getColumn();
                    if (discriminatorColumn != null) {
                        discriminatorColumnName = discriminatorColumn.getName();
                    }
                    if (discriminatorConfig.getFormula() != null) {
                        discriminatorColumnName = discriminatorConfig.getFormula();
                    }
                }
            }
            //NOTE: this will build the set for the in clause if it has sublcasses
            Set<String> discSet = buildDiscriminatorSet((HibernatePersistentEntity) referenced);
            String inclause = DefaultGroovyMethods.join(discSet, ",");

            collection.setWhere(discriminatorColumnName + " in (" + inclause + ")");
        }

        OneToMany oneToMany = (OneToMany) collection.getElement();
        String associatedClassName = oneToMany.getReferencedEntityName();

        associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
        // if there is no persistent class for the association throw exception
        if (associatedClass == null) {
            throw new MappingException(
                    "Association references unmapped class: " + oneToMany.getReferencedEntityName());
        }

        oneToMany.setAssociatedClass(associatedClass);
        if (shouldBindCollectionWithForeignKey(property)) {
            collection.setCollectionTable(associatedClass.getTable());
        }

        bindCollectionForPropertyConfig(collection, propConfig);
    }

    if (referenced != null && referenced.isMultiTenant()) {
        String filterCondition = getMultiTenantFilterCondition(sessionFactoryBeanName, referenced);
        if (filterCondition != null) {
            collection.addFilter(GormProperties.TENANT_IDENTITY, filterCondition, true,
                    Collections.<String, String>emptyMap(), Collections.<String, String>emptyMap());
        }
    }

    if (isSorted(property)) {
        collection.setSorted(true);
    }

    // setup the primary key references
    DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses);

    // link a bidirectional relationship
    if (property.isBidirectional()) {
        Association otherSide = property.getInverseSide();
        if ((otherSide instanceof org.grails.datastore.mapping.model.types.ToOne)
                && shouldBindCollectionWithForeignKey(property)) {
            linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
        } else if ((otherSide instanceof ManyToMany) || Map.class.isAssignableFrom(property.getType())) {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    } else {
        if (hasJoinKeyMapping(propConfig)) {
            bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings);
        } else {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    }
    collection.setKey(key);

    // get cache config
    if (propConfig != null) {
        CacheConfig cacheConfig = propConfig.getCache();
        if (cacheConfig != null) {
            collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
        }
    }

    // if we have a many-to-many
    final boolean isManyToMany = property instanceof ManyToMany;
    if (isManyToMany || isBidirectionalOneToManyMap(property)) {
        PersistentProperty otherSide = property.getInverseSide();

        if (property.isBidirectional()) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getOwner().getName() + "."
                        + otherSide.getName() + " -> " + collection.getCollectionTable().getName()
                        + " as ManyToOne");
            ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable());
            bindManyToMany((Association) otherSide, element, mappings, sessionFactoryBeanName);
            collection.setElement(element);
            bindCollectionForPropertyConfig(collection, propConfig);
            if (property.isCircular()) {
                collection.setInverse(false);
            }
        } else {
            // TODO support unidirectional many-to-many
        }
    } else if (shouldCollectionBindWithJoinColumn(property)) {
        bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName);

    } else if (isUnidirectionalOneToMany(property)) {
        // for non-inverse one-to-many, with a not-null fk, add a backref!
        // there are problems with list and map mappings and join columns relating to duplicate key constraints
        // TODO change this when HHH-1268 is resolved
        bindUnidirectionalOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, mappings,
                collection);
    }
}