Example usage for org.hibernate.mapping Collection isOneToMany

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

Introduction

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

Prototype

public boolean isOneToMany() 

Source Link

Usage

From source file:com.blazebit.persistence.integration.hibernate.CustomPersisterClassResolver.java

License:Apache License

@Override
public Class<? extends CollectionPersister> getCollectionPersisterClass(Collection metadata) {
    return metadata.isOneToMany() ? CustomOneToManyPersister.class : CustomBasicCollectionPersister.class;
}

From source file:com.medigy.tool.persist.hibernate.dbdd.MedigyDatabaseStructureRules.java

License:Open Source License

public boolean isParentRelationship(final TableStructure structure, final ForeignKey foreignKey) {
    for (Iterator colls = structure.getConfiguration().getCollectionMappings(); colls.hasNext();) {
        final Collection coll = (Collection) colls.next();
        if (coll.isOneToMany()) {
            if (foreignKey.getReferencedTable() == coll.getOwner().getTable()
                    && foreignKey.getTable() == coll.getCollectionTable())
                return true;
        }//from w ww. j a va 2s.co  m
    }

    return false;
}

From source file:com.netspective.tool.hibernate.document.diagram.HibernateDiagramGenerator.java

License:Open Source License

public boolean isParentRelationship(final ForeignKey foreignKey) {
    for (Iterator colls = getConfiguration().getCollectionMappings(); colls.hasNext();) {
        final Collection coll = (Collection) colls.next();
        if (coll.isOneToMany()) {
            // for parents, we put the crow arrow pointing to us (the source becomes the parent, not the child -- this way it will look like a tree)
            if (foreignKey.getReferencedTable() == coll.getOwner().getTable()
                    && foreignKey.getTable() == coll.getCollectionTable())
                return true;
        }/*  w  w w. j a  va2s  . com*/
    }

    return false;
}

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

License:Open Source License

/**
 * Generate sql scripts/*from  w  ww .j  av  a 2s  . 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.");
        }/* ww w .  j a v  a2 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.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.");
        }/* ww w .jav a2 s .  com*/
        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.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.");
        }/*  w  ww  .j a va2s.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  .  j  a v a2  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);
    }
}

From source file:org.sns.tool.hibernate.analyzer.HibernateAnalysis.java

License:Open Source License

public boolean isParentRelationship(final ForeignKey foreignKey) {
    for (Iterator colls = getConfiguration().getCollectionMappings(); colls.hasNext();) {
        final Collection coll = (Collection) colls.next();
        if (coll.isOneToMany()) {
            if (foreignKey.getReferencedTable() == coll.getOwner().getTable()
                    && foreignKey.getTable() == coll.getCollectionTable())
                return true;
        }/*from   w  ww.ja va2s.  c o m*/
    }

    return false;
}