Example usage for org.hibernate.mapping Collection getRole

List of usage examples for org.hibernate.mapping Collection getRole

Introduction

In this page you can find the example usage for org.hibernate.mapping Collection getRole.

Prototype

public String getRole() 

Source Link

Usage

From source file:com.fiveamsolutions.nci.commons.util.CsmEnabledHibernateHelper.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w w w. j  a  va  2 s  .  c  o  m*/
 */
@Override
protected void modifyConfig() {
    super.modifyConfig();
    if (this.authorizationManager != null) {
        if (this.userSecurityFilters) {
            InstanceLevelSecurityHelper.addFilters(this.authorizationManager, getConfiguration());
        } else {
            InstanceLevelSecurityHelper.addFiltersForGroups(this.authorizationManager, getConfiguration());
        }
    }
    @SuppressWarnings("unchecked")
    Iterator<Collection> it = getConfiguration().getCollectionMappings();
    final String role = Group.class.getName() + ".users";
    while (it.hasNext()) {
        Collection c = it.next();
        if (c.getRole().equals(role)) {
            c.setLazy(true);
            c.setExtraLazy(true);
        }
    }
}

From source file:edu.wustl.common.util.dbManager.HibernateMetaData.java

License:BSD License

/**This function saves the relation data in HashSet.
 * @param col this is the collection which contains all data
 * @param rel_type this is Many-To-Many ot Many-To-One
 * @throws Exception//from   w w  w  . j a  v a2  s . c o m
 */
private static void saveRelations(Collection col, String rel_type) throws Exception {
    String className = col.getOwner().getClassName();
    String relatedClassName = col.getElement().getType().getName();
    String roleAttribute = col.getRole();
    String relationType = rel_type;
    String relationTable = col.getElement().getTable().getName();
    String keyId = getKeyId(roleAttribute);
    String roleId = getRoleKeyId(roleAttribute);

    ClassRelationshipData hmc = new ClassRelationshipData(className, relatedClassName, roleAttribute,
            relationType, relationTable, keyId, roleId);
    mappings.add(hmc);

    List list1 = HibernateMetaData.getSubClassList(col.getOwner().getClassName());
    for (int i = 0; i < list1.size(); i++) {
        hmc = new ClassRelationshipData(list1.get(i).toString(), relatedClassName, roleAttribute, relationType,
                relationTable, keyId, roleId);
        mappings.add(hmc);
    }

    List list2 = HibernateMetaData.getSubClassList(col.getElement().getType().getName());
    for (int i = 0; i < list2.size(); i++) {
        hmc = new ClassRelationshipData(className, list2.get(i).toString(), roleAttribute, relationType,
                relationTable, keyId, roleId);
        mappings.add(hmc);
    }
}

From source file:org.beangle.commons.orm.hibernate.internal.OverrideConfiguration.java

License:Open Source License

private void configSchema() {
    TableNamingStrategy namingStrategy = null;
    if (getNamingStrategy() instanceof RailsNamingStrategy) {
        namingStrategy = ((RailsNamingStrategy) getNamingStrategy()).getTableNamingStrategy();
    }//from  www . ja  v a  2 s.co m

    if (null == namingStrategy)
        return;
    else {
        // Update SeqGenerator's static variable.
        // Because generator is init by hibernate,cannot inject namingStrategy.
        TableSeqGenerator.namingStrategy = namingStrategy;
    }

    if (namingStrategy.isMultiSchema()) {
        for (PersistentClass clazz : classes.values()) {
            String schema = namingStrategy.getSchema(clazz.getEntityName());
            if (null != schema)
                clazz.getTable().setSchema(schema);
        }

        for (Collection collection : collections.values()) {
            final Table table = collection.getCollectionTable();
            if (null == table)
                continue;
            String schema = namingStrategy.getSchema(collection.getRole());
            if (null != schema)
                table.setSchema(schema);
        }
    }
}

From source file:org.beangle.orm.hibernate.internal.OverrideConfiguration.java

License:Open Source License

/**
 * Config table's schema by TableNamingStrategy
 *//*from w  w w.  j  a  va 2  s. co m*/
private void configSchema() {
    TableNamingStrategy namingStrategy = null;
    if (getNamingStrategy() instanceof RailsNamingStrategy) {
        namingStrategy = ((RailsNamingStrategy) getNamingStrategy()).getTableNamingStrategy();
    }

    if (null == namingStrategy)
        return;
    else {
        // Update SeqGenerator's static variable.
        // Because generator is init by hibernate,cannot inject namingStrategy.
        TableSeqGenerator.namingStrategy = namingStrategy;
    }

    if (namingStrategy.isMultiSchema()) {
        for (PersistentClass clazz : classes.values()) {
            String schema = namingStrategy.getSchema(clazz.getEntityName());
            if (null != schema)
                clazz.getTable().setSchema(schema);
        }

        for (Collection collection : collections.values()) {
            final Table table = collection.getCollectionTable();
            if (null == table)
                continue;
            String schema = namingStrategy.getSchema(collection.getRole());
            if (null != schema)
                table.setSchema(schema);
        }
    }
}

From source file:org.beangle.orm.hibernate.tool.DdlGenerator.java

License:Open Source License

/**
 * Generate sql scripts// w  w  w .j  av  a 2  s  .  c  om
 * 
 * @param fileName
 * @param packageName
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void gen(String fileName, String packageName) throws Exception {
    configuration = ConfigBuilder.build(new OverrideConfiguration());
    mapping = configuration.buildMapping();
    defaultCatalog = configuration.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    defaultSchema = configuration.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
    configuration.getProperties().put(Environment.DIALECT, dialect);
    // 1. first process class mapping
    Iterator<PersistentClass> iterpc = configuration.getClassMappings();
    while (iterpc.hasNext()) {
        PersistentClass pc = iterpc.next();
        Class<?> clazz = pc.getMappedClass();
        if (isNotBlank(packageName) && !clazz.getPackage().getName().startsWith(packageName))
            continue;
        // add comment to table and column
        pc.getTable().setComment(messages.get(clazz, clazz.getSimpleName()));
        commentProperty(clazz, pc.getTable(), pc.getIdentifierProperty());
        commentProperties(clazz, pc.getTable(), pc.getPropertyIterator());
        // generator sequence sql
        if (pc instanceof RootClass) {
            IdentifierGenerator ig = pc.getIdentifier().createIdentifierGenerator(
                    configuration.getIdentifierGeneratorFactory(), dialect, defaultCatalog, defaultSchema,
                    (RootClass) pc);
            if (ig instanceof PersistentIdentifierGenerator) {
                String[] lines = ((PersistentIdentifierGenerator) ig).sqlCreateStrings(dialect);
                sequences.addAll(Arrays.asList(lines));
            }
        }
        // generater table sql
        generateTableSql(pc.getTable());
    }

    // 2. process collection mapping
    Iterator<Collection> itercm = configuration.getCollectionMappings();
    while (itercm.hasNext()) {
        Collection col = itercm.next();
        if (isNotBlank(packageName) && !col.getRole().startsWith(packageName))
            continue;
        // collection sequences
        if (col.isIdentified()) {
            IdentifierGenerator ig = ((IdentifierCollection) col).getIdentifier().createIdentifierGenerator(
                    configuration.getIdentifierGeneratorFactory(), dialect, defaultCatalog, defaultSchema,
                    null);

            if (ig instanceof PersistentIdentifierGenerator) {
                String[] lines = ((PersistentIdentifierGenerator) ig).sqlCreateStrings(dialect);
                sequences.addAll(Arrays.asList(lines));
            }
        }
        // collection table
        if (!col.isOneToMany()) {
            Table table = col.getCollectionTable();
            String owner = col.getTable().getComment();
            Class<?> ownerClass = col.getOwner().getMappedClass();
            // resolved nested compoent name in collection's role
            String colName = substringAfter(col.getRole(), col.getOwnerEntityName() + ".");
            if (colName.contains("."))
                ownerClass = getPropertyType(col.getOwner(), substringBeforeLast(colName, "."));
            table.setComment(owner + "-" + messages.get(ownerClass, substringAfterLast(col.getRole(), ".")));

            Column keyColumn = table.getColumn((Column) col.getKey().getColumnIterator().next());
            if (null != keyColumn)
                keyColumn.setComment(owner + " ID");

            if (col instanceof IndexedCollection) {
                IndexedCollection idxCol = (IndexedCollection) col;
                Value idx = idxCol.getIndex();
                if (idx instanceof ToOne)
                    commentToOne((ToOne) idx, (Column) idx.getColumnIterator().next());
            }
            if (col.getElement() instanceof ManyToOne) {
                Column valueColumn = (Column) col.getElement().getColumnIterator().next();
                commentToOne((ManyToOne) col.getElement(), valueColumn);
            } else if (col.getElement() instanceof Component) {
                Component cp = (Component) col.getElement();
                commentProperties(cp.getComponentClass(), table, cp.getPropertyIterator());
            }
            generateTableSql(col.getCollectionTable());
        }
    }
    Set<String> commentSet = CollectUtils.newHashSet(comments);
    comments.clear();
    comments.addAll(commentSet);
    // 3. export to files
    for (String key : files.keySet()) {
        List<List<String>> sqls = files.get(key);
        FileWriter writer = new FileWriter(fileName + "/" + key, false);
        writes(writer, sqls);
        writer.flush();
        writer.close();
    }
}

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.");
        }// www .  j  ava 2 s.  c om
        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.AbstractGrailsDomainBinder.java

License:Apache License

/**
 * Binds a unidirectional one-to-many creating a psuedo back reference property in the process.
 *
 * @param property//from ww  w .  j a  v a2  s.com
 * @param mappings
 * @param collection
 */
protected void bindUnidirectionalOneToMany(GrailsDomainClassProperty property, Mappings mappings,
        Collection collection) {
    Value v = collection.getElement();
    v.createForeignKey();
    String entityName;
    if (v instanceof ManyToOne) {
        ManyToOne manyToOne = (ManyToOne) v;

        entityName = manyToOne.getReferencedEntityName();
    } else {
        entityName = ((OneToMany) v).getReferencedEntityName();
    }
    collection.setInverse(false);
    PersistentClass referenced = mappings.getClass(entityName);
    Backref prop = new Backref();
    prop.setEntityName(property.getDomainClass().getFullName());
    prop.setName(UNDERSCORE + addUnderscore(property.getDomainClass().getShortName(), property.getName())
            + "Backref");
    prop.setUpdateable(false);
    prop.setInsertable(true);
    prop.setCollectionRole(collection.getRole());
    prop.setValue(collection.getKey());
    prop.setOptional(true);

    referenced.addProperty(prop);
}

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.");
        }//w w  w.  j  ava 2  s.co 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.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder.java

License:Apache License

/**
 * Binds a unidirectional one-to-many creating a psuedo back reference property in the process.
 *
 * @param property//from w ww.  ja v a2  s  .  co  m
 * @param mappings
 * @param collection
 */
private static void bindUnidirectionalOneToMany(GrailsDomainClassProperty property, Mappings mappings,
        Collection collection) {
    Value v = collection.getElement();
    v.createForeignKey();
    String entityName;
    if (v instanceof ManyToOne) {
        ManyToOne manyToOne = (ManyToOne) v;

        entityName = manyToOne.getReferencedEntityName();
    } else {
        entityName = ((OneToMany) v).getReferencedEntityName();
    }
    collection.setInverse(false);
    PersistentClass referenced = mappings.getClass(entityName);
    Backref prop = new Backref();
    prop.setEntityName(property.getDomainClass().getFullName());
    prop.setName(UNDERSCORE + addUnderscore(property.getDomainClass().getShortName(), property.getName())
            + "Backref");
    prop.setUpdateable(false);
    prop.setInsertable(true);
    prop.setCollectionRole(collection.getRole());
    prop.setValue(collection.getKey());
    prop.setOptional(true);

    referenced.addProperty(prop);
}

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 a2  s .co m
        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);
    }
}