Example usage for org.hibernate MappingException MappingException

List of usage examples for org.hibernate MappingException MappingException

Introduction

In this page you can find the example usage for org.hibernate MappingException MappingException.

Prototype

public MappingException(String message) 

Source Link

Document

Constructs a MappingException using the given information.

Usage

From source file:org.babyfish.hibernate.internal.SessionImplWrapper.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static XQuery getNamedQuery(XSessionImplementor sessionProxy, String queryName)
        throws HibernateException {
    errorIfClosed(sessionProxy.getRawSessionImpl());
    checkTransactionSynchStatus(sessionProxy.getRawSessionImpl());
    NamedQueryDefinition nqd = sessionProxy.getFactory().getNamedQuery(queryName);
    if (nqd != null) {
        String queryString = nqd.getQueryString();
        XQueryPlan xQueryPlan = (XQueryPlan) sessionProxy.getFactory().getQueryPlanCache()
                .getHQLQueryPlan(queryString, false, sessionProxy.getRawSessionImpl().getEnabledFilters());
        XQuery query = new XQueryImpl(queryString, nqd.getFlushMode(), sessionProxy,
                xQueryPlan.getParameterMetadata());
        query.setComment("named HQL query " + queryName);
        initQuery(sessionProxy.getRawSessionImpl(), query, nqd);
        return query;
    }/*from ww w.  j  ava 2 s  . c  o  m*/
    NamedSQLQueryDefinition nsqlqd = sessionProxy.getFactory().getNamedSQLQuery(queryName);
    if (nsqlqd != null) {
        throw new MappingException("Name query \"" + queryName + "\" is a native query");
    }
    throw new MappingException("Named query not known: " + queryName);
}

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

License:Apache License

protected void bindMapSecondPass(GrailsDomainClassProperty property, Mappings mappings,
        Map<?, ?> persistentClasses, org.hibernate.mapping.Map map, String sessionFactoryBeanName) {
    bindCollectionSecondPass(property, mappings, persistentClasses, map, sessionFactoryBeanName);

    SimpleValue value = new SimpleValue(mappings, map.getCollectionTable());

    bindSimpleValue(getIndexColumnType(property, STRING_TYPE), value, true,
            getIndexColumnName(property, sessionFactoryBeanName), mappings);
    PropertyConfig pc = getPropertyConfig(property);
    if (pc != null && pc.getIndexColumn() != null) {
        bindColumnConfigToColumn(getColumnForSimpleValue(value), getSingleColumnConfig(pc.getIndexColumn()));
    }/*from  www .  ja  v  a  2s.c o  m*/

    if (!value.isTypeSpecified()) {
        throw new MappingException("map index element must specify a type: " + map.getRole());
    }
    map.setIndex(value);

    if (!property.isOneToMany() && !property.isManyToMany()) {
        SimpleValue elt = new SimpleValue(mappings, map.getCollectionTable());
        map.setElement(elt);

        String typeName = getTypeName(property, getPropertyConfig(property),
                getMapping(property.getDomainClass()));
        if (typeName == null) {
            if (property.isBasicCollectionType()) {
                typeName = property.getReferencedPropertyType().getName();
            } else {
                typeName = StandardBasicTypes.STRING.getName();
            }
        }
        bindSimpleValue(typeName, elt, false, getMapElementName(property, sessionFactoryBeanName), mappings);

        elt.setTypeName(typeName);

        map.setInverse(false);
    } else {
        map.setInverse(false);
    }
}

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

License:Apache License

protected void bindListSecondPass(GrailsDomainClassProperty property, Mappings mappings,
        Map<?, ?> persistentClasses, org.hibernate.mapping.List list, String sessionFactoryBeanName) {

    bindCollectionSecondPass(property, mappings, persistentClasses, list, sessionFactoryBeanName);

    String columnName = getIndexColumnName(property, sessionFactoryBeanName);
    final boolean isManyToMany = property.isManyToMany();

    if (isManyToMany && !property.isOwningSide()) {
        throw new MappingException("Invalid association [" + property.getDomainClass().getName() + "->"
                + property.getName()//from  w w w .  j  a  v a2  s .  c  o  m
                + "]. List collection types only supported on the owning side of a many-to-many relationship.");
    }

    Table collectionTable = list.getCollectionTable();
    SimpleValue iv = new SimpleValue(mappings, collectionTable);
    bindSimpleValue("integer", iv, true, columnName, mappings);
    iv.setTypeName("integer");
    list.setIndex(iv);
    list.setBaseIndex(0);
    list.setInverse(false);

    Value v = list.getElement();
    v.createForeignKey();

    if (property.isBidirectional()) {

        String entityName;
        Value element = list.getElement();
        if (element instanceof ManyToOne) {
            ManyToOne manyToOne = (ManyToOne) element;
            entityName = manyToOne.getReferencedEntityName();
        } else {
            entityName = ((OneToMany) element).getReferencedEntityName();
        }

        PersistentClass referenced = mappings.getClass(entityName);

        Class<?> mappedClass = referenced.getMappedClass();
        Mapping m = getMapping(mappedClass);

        boolean compositeIdProperty = isCompositeIdProperty(m, property.getOtherSide());
        if (!compositeIdProperty) {
            Backref prop = new Backref();
            prop.setEntityName(property.getDomainClass().getFullName());
            prop.setName(UNDERSCORE
                    + addUnderscore(property.getDomainClass().getShortName(), property.getName()) + "Backref");
            prop.setSelectable(false);
            prop.setUpdateable(false);
            if (isManyToMany) {
                prop.setInsertable(false);
            }
            prop.setCollectionRole(list.getRole());
            prop.setValue(list.getKey());

            DependantValue value = (DependantValue) prop.getValue();
            if (!property.isCircular()) {
                value.setNullable(false);
            }
            value.setUpdateable(true);
            prop.setOptional(false);

            referenced.addProperty(prop);
        }

        if ((!list.getKey().isNullable() && !list.isInverse()) || compositeIdProperty) {
            IndexBackref ib = new IndexBackref();
            ib.setName(UNDERSCORE + property.getName() + "IndexBackref");
            ib.setUpdateable(false);
            ib.setSelectable(false);
            if (isManyToMany) {
                ib.setInsertable(false);
            }
            ib.setCollectionRole(list.getRole());
            ib.setEntityName(list.getOwner().getEntityName());
            ib.setValue(list.getIndex());
            referenced.addProperty(ib);
        }
    }
}

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  ww w .  j a  v 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.AbstractGrailsDomainBinder.java

License:Apache License

protected void bindCollectionWithJoinTable(GrailsDomainClassProperty property, Mappings mappings,
        Collection collection, PropertyConfig config, String sessionFactoryBeanName) {

    NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName);

    SimpleValue element;/*  w w w  .j av a 2 s  . co  m*/
    if (property.isBasicCollectionType()) {
        element = new SimpleValue(mappings, collection.getCollectionTable());
    } else {
        // for a normal unidirectional one-to-many we use a join column
        element = new ManyToOne(mappings, collection.getCollectionTable());
        bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element);
    }
    collection.setInverse(false);

    String columnName;

    final boolean hasJoinColumnMapping = hasJoinColumnMapping(config);
    if (property.isBasicCollectionType()) {
        final Class<?> referencedType = property.getReferencedPropertyType();
        String className = referencedType.getName();
        final boolean isEnum = referencedType.isEnum();
        if (hasJoinColumnMapping) {
            columnName = config.getJoinTable().getColumn().getName();
        } else {
            columnName = isEnum ? namingStrategy.propertyToColumnName(className)
                    : addUnderscore(namingStrategy.propertyToColumnName(property.getName()),
                            namingStrategy.propertyToColumnName(className));
        }

        if (isEnum) {
            bindEnumType(property, referencedType, element, columnName);
        } else {

            String typeName = getTypeName(property, config, getMapping(property.getDomainClass()));
            if (typeName == null) {
                Type type = mappings.getTypeResolver().basic(className);
                if (type != null) {
                    typeName = type.getName();
                }
            }
            if (typeName == null) {
                String domainName = property.getDomainClass().getName();
                throw new MappingException("Missing type or column for column[" + columnName + "] on domain["
                        + domainName + "] referencing[" + className + "]");
            }

            bindSimpleValue(typeName, element, true, columnName, mappings);
            if (hasJoinColumnMapping) {
                bindColumnConfigToColumn(getColumnForSimpleValue(element), config.getJoinTable().getColumn());
            }
        }
    } else {
        final GrailsDomainClass domainClass = property.getReferencedDomainClass();

        Mapping m = getMapping(domainClass.getClazz());
        if (hasCompositeIdentifier(m)) {
            CompositeIdentity ci = (CompositeIdentity) m.getIdentity();
            bindCompositeIdentifierToManyToOne(property, element, ci, domainClass, EMPTY_PATH,
                    sessionFactoryBeanName);
        } else {
            if (hasJoinColumnMapping) {
                columnName = config.getJoinTable().getColumn().getName();
            } else {
                columnName = namingStrategy.propertyToColumnName(domainClass.getPropertyName())
                        + FOREIGN_KEY_SUFFIX;
            }

            bindSimpleValue("long", element, true, columnName, mappings);
        }
    }

    collection.setElement(element);

    bindCollectionForPropertyConfig(collection, config);
}

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

License:Apache License

protected void bindIdentity(GrailsDomainClass domainClass, RootClass root, Mappings mappings,
        Mapping gormMapping, String sessionFactoryBeanName) {

    GrailsDomainClassProperty identifierProp = domainClass.getIdentifier();
    if (gormMapping == null) {
        bindSimpleId(identifierProp, root, mappings, null, sessionFactoryBeanName);
        return;/*from   w w w  . ja va 2  s  .c  o m*/
    }

    Object id = gormMapping.getIdentity();
    if (id instanceof CompositeIdentity) {
        bindCompositeId(domainClass, root, (CompositeIdentity) id, mappings, sessionFactoryBeanName);
    } else {
        final Identity identity = (Identity) id;
        String propertyName = identity.getName();
        if (propertyName != null) {
            GrailsDomainClassProperty namedIdentityProp = domainClass.getPropertyByName(propertyName);
            if (namedIdentityProp == null) {
                throw new MappingException("Mapping specifies an identifier property name that doesn't exist ["
                        + propertyName + "]");
            }
            if (!namedIdentityProp.equals(identifierProp)) {
                identifierProp = namedIdentityProp;
            }
        }
        bindSimpleId(identifierProp, root, mappings, identity, sessionFactoryBeanName);
    }
}

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

License:Apache License

protected void bindCompositeId(GrailsDomainClass domainClass, RootClass root,
        CompositeIdentity compositeIdentity, Mappings mappings, String sessionFactoryBeanName) {
    Component id = new Component(mappings, root);
    id.setNullValue("undefined");
    root.setIdentifier(id);/* www  .  j a  va2 s . c  o  m*/
    root.setEmbeddedIdentifier(true);
    id.setComponentClassName(domainClass.getFullName());
    id.setKey(true);
    id.setEmbedded(true);

    String path = qualify(root.getEntityName(), "id");

    id.setRoleName(path);

    String[] props = compositeIdentity.getPropertyNames();
    for (String propName : props) {
        GrailsDomainClassProperty property = domainClass.getPropertyByName(propName);
        if (property == null) {
            throw new MappingException(
                    "Property [" + propName + "] referenced in composite-id mapping of class ["
                            + domainClass.getFullName() + "] is not a valid property!");
        }

        bindComponentProperty(id, null, property, root, "", root.getTable(), mappings, sessionFactoryBeanName);
    }
}

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

License:Apache License

/**
 * Creates and binds the properties for the specified Grails domain class and PersistentClass
 * and binds them to the Hibernate runtime meta model
 *
 * @param domainClass     The Grails domain class
 * @param persistentClass The Hibernate PersistentClass instance
 * @param mappings        The Hibernate Mappings instance
 * @param sessionFactoryBeanName  the session factory bean name
 *//*ww w .  j  av  a  2s  .  com*/
protected void createClassProperties(GrailsDomainClass domainClass, PersistentClass persistentClass,
        Mappings mappings, String sessionFactoryBeanName) {

    GrailsDomainClassProperty[] persistentProperties = domainClass.getPersistentProperties();
    Table table = persistentClass.getTable();

    Mapping gormMapping = getMapping(domainClass.getClazz());

    if (gormMapping != null) {
        table.setComment(gormMapping.getComment());
    }

    for (GrailsDomainClassProperty currentGrailsProp : persistentProperties) {

        // if its inherited skip
        boolean isBidirectionalManyToOne = isBidirectionalManyToOne(currentGrailsProp);
        if (currentGrailsProp.isInherited()) {
            continue;
        }
        if (currentGrailsProp.isInherited() && isBidirectionalManyToOne && currentGrailsProp.isCircular()) {
            continue;
        }
        if (isCompositeIdProperty(gormMapping, currentGrailsProp))
            continue;
        if (isIdentityProperty(gormMapping, currentGrailsProp))
            continue;

        if (LOG.isDebugEnabled()) {
            LOG.debug("[GrailsDomainBinder] Binding persistent property [" + currentGrailsProp.getName() + "]");
        }

        Value value = null;

        // see if it's a collection type
        CollectionType collectionType = CT.collectionTypeForClass(currentGrailsProp.getType());

        Class<?> userType = getUserType(currentGrailsProp);

        if (userType != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                        + "] as SimpleValue");
            }
            value = new SimpleValue(mappings, table);
            bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings,
                    sessionFactoryBeanName);
        } else if (collectionType != null) {
            String typeName = getTypeName(currentGrailsProp, getPropertyConfig(currentGrailsProp), gormMapping);
            if ("serializable".equals(typeName)) {
                value = new SimpleValue(mappings, table);
                bindSimpleValue(typeName, (SimpleValue) value, currentGrailsProp.isOptional(),
                        getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null,
                                sessionFactoryBeanName),
                        mappings);
            } else {
                // create collection
                Collection collection = collectionType.create(currentGrailsProp, persistentClass, EMPTY_PATH,
                        mappings, sessionFactoryBeanName);
                mappings.addCollection(collection);
                value = collection;
            }
        } else if (currentGrailsProp.isEnum()) {
            value = new SimpleValue(mappings, table);
            bindEnumType(currentGrailsProp, (SimpleValue) value, EMPTY_PATH, sessionFactoryBeanName);
        }
        // work out what type of relationship it is and bind value
        else if (currentGrailsProp.isManyToOne()) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                        + "] as ManyToOne");

            value = new ManyToOne(mappings, table);
            bindManyToOne(currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings, sessionFactoryBeanName);
        } else if (currentGrailsProp.isOneToOne() && userType == null) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                        + "] as OneToOne");

            if (currentGrailsProp.isHasOne() && !currentGrailsProp.isBidirectional()) {
                throw new MappingException("hasOne property [" + currentGrailsProp.getDomainClass().getName()
                        + "." + currentGrailsProp.getName()
                        + "] is not bidirectional. Specify the other side of the relationship!");
            } else if (canBindOneToOneWithSingleColumnAndForeignKey(currentGrailsProp)) {
                value = new OneToOne(mappings, table, persistentClass);
                bindOneToOne(currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName);
            } else {
                if (currentGrailsProp.isHasOne() && currentGrailsProp.isBidirectional()) {
                    value = new OneToOne(mappings, table, persistentClass);
                    bindOneToOne(currentGrailsProp, (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName);
                } else {
                    value = new ManyToOne(mappings, table);
                    bindManyToOne(currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings,
                            sessionFactoryBeanName);
                }
            }
        } else if (currentGrailsProp.isEmbedded()) {
            value = new Component(mappings, persistentClass);

            bindComponent((Component) value, currentGrailsProp, true, mappings, sessionFactoryBeanName);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                        + "] as SimpleValue");
            }
            value = new SimpleValue(mappings, table);
            bindSimpleValue(currentGrailsProp, null, (SimpleValue) value, EMPTY_PATH, mappings,
                    sessionFactoryBeanName);
        }

        if (value != null) {
            Property property = createProperty(value, persistentClass, currentGrailsProp, mappings);
            persistentClass.addProperty(property);
        }
    }

    bindNaturalIdentifier(table, gormMapping, persistentClass);
}

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

License:Apache License

private static void bindMapSecondPass(GrailsDomainClassProperty property, Mappings mappings,
        Map<?, ?> persistentClasses, org.hibernate.mapping.Map map, String sessionFactoryBeanName) {
    bindCollectionSecondPass(property, mappings, persistentClasses, map, sessionFactoryBeanName);

    SimpleValue value = new SimpleValue(mappings, map.getCollectionTable());

    bindSimpleValue(getIndexColumnType(property, STRING_TYPE), value, true,
            getIndexColumnName(property, sessionFactoryBeanName), mappings);
    PropertyConfig pc = getPropertyConfig(property);
    if (pc != null && pc.getIndexColumn() != null) {
        bindColumnConfigToColumn(getColumnForSimpleValue(value), getSingleColumnConfig(pc.getIndexColumn()));
    }/* w  ww .jav  a2 s  .  c  om*/

    if (!value.isTypeSpecified()) {
        throw new MappingException("map index element must specify a type: " + map.getRole());
    }
    map.setIndex(value);

    if (!property.isOneToMany() && !property.isManyToMany()) {
        SimpleValue elt = new SimpleValue(mappings, map.getCollectionTable());
        map.setElement(elt);

        String typeName = getTypeName(property, getPropertyConfig(property),
                getMapping(property.getDomainClass()));
        if (typeName == null) {
            if (property.isBasicCollectionType()) {
                typeName = property.getReferencedPropertyType().getName();
            } else {
                typeName = StandardBasicTypes.STRING.getName();
            }
        }
        bindSimpleValue(typeName, elt, false, getMapElementName(property, sessionFactoryBeanName), mappings);

        elt.setTypeName(typeName);

        map.setInverse(false);
    } else {
        map.setInverse(false);
    }
}

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 ww .  j  a  v a 2s. 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 = 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);
    }
}