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.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
 *///  w  w  w  .j a  va  2s.c  om
protected void createClassProperties(HibernatePersistentEntity domainClass, PersistentClass persistentClass,
        Mappings mappings, String sessionFactoryBeanName) {

    final List<PersistentProperty> persistentProperties = domainClass.getPersistentProperties();
    Table table = persistentClass.getTable();

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

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

    List<Embedded> embedded = new ArrayList<>();
    for (PersistentProperty currentGrailsProp : persistentProperties) {

        // if its inherited skip
        if (currentGrailsProp.isInherited()) {
            continue;
        }
        if (currentGrailsProp.getName().equals(GormProperties.VERSION))
            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.isNullable(),
                        getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null,
                                sessionFactoryBeanName),
                        mappings);
            } else {
                // create collection
                Collection collection = collectionType.create((ToMany) currentGrailsProp, persistentClass,
                        EMPTY_PATH, mappings, sessionFactoryBeanName);
                mappings.addCollection(collection);
                value = collection;
            }
        } else if (currentGrailsProp.getType().isEnum()) {
            value = new SimpleValue(mappings, table);
            bindEnumType(currentGrailsProp, (SimpleValue) value, EMPTY_PATH, sessionFactoryBeanName);
        } else if (currentGrailsProp instanceof Association) {
            Association association = (Association) currentGrailsProp;
            if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.ManyToOne) {
                if (LOG.isDebugEnabled())
                    LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                            + "] as ManyToOne");

                value = new ManyToOne(mappings, table);
                bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings,
                        sessionFactoryBeanName);
            } else if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.OneToOne
                    && userType == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                            + "] as OneToOne");
                }

                final boolean isHasOne = isHasOne(association);
                if (isHasOne && !association.isBidirectional()) {
                    throw new MappingException("hasOne property [" + currentGrailsProp.getOwner().getName()
                            + "." + currentGrailsProp.getName()
                            + "] is not bidirectional. Specify the other side of the relationship!");
                } else if (canBindOneToOneWithSingleColumnAndForeignKey((Association) currentGrailsProp)) {
                    value = new OneToOne(mappings, table, persistentClass);
                    bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp,
                            (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName);
                } else {
                    if (isHasOne && association.isBidirectional()) {
                        value = new OneToOne(mappings, table, persistentClass);
                        bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp,
                                (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName);
                    } else {
                        value = new ManyToOne(mappings, table);
                        bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings,
                                sessionFactoryBeanName);
                    }
                }
            } else if (currentGrailsProp instanceof Embedded) {
                embedded.add((Embedded) currentGrailsProp);
                continue;
            }
        }
        // work out what type of relationship it is and bind value
        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);
        }
    }

    for (Embedded association : embedded) {
        Value value = new Component(mappings, persistentClass);

        bindComponent((Component) value, association, true, mappings, sessionFactoryBeanName);
        Property property = createProperty(value, persistentClass, association, mappings);
        persistentClass.addProperty(property);
    }

    bindNaturalIdentifier(table, gormMapping, persistentClass);
}

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

License:Apache License

protected void bindMapSecondPass(ToMany property, InFlightMetadataCollector 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(property, getColumnForSimpleValue(value),
                getSingleColumnConfig(pc.getIndexColumn()));
    }//from   w w w .j  a v a2  s .c o m

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

    if (!(property instanceof org.grails.datastore.mapping.model.types.OneToMany)
            && !(property instanceof ManyToMany)) {

        SimpleValue elt = new SimpleValue(mappings, map.getCollectionTable());
        map.setElement(elt);

        String typeName = getTypeName(property, getPropertyConfig(property), getMapping(property.getOwner()));
        if (typeName == null) {

            if (property instanceof Basic) {
                Basic basic = (Basic) property;
                typeName = basic.getComponentType().getName();
            }
        }
        if (typeName == null || typeName.equals(Object.class.getName())) {
            typeName = StandardBasicTypes.STRING.getName();
        }
        bindSimpleValue(typeName, elt, false, getMapElementName(property, sessionFactoryBeanName), mappings);

        elt.setTypeName(typeName);
    }

    map.setInverse(false);
}

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

License:Apache License

protected void bindListSecondPass(ToMany property, InFlightMetadataCollector 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 instanceof ManyToMany;

    if (isManyToMany && !property.isOwningSide()) {
        throw new MappingException("Invalid association [" + property
                + "]. List collection types only supported on the owning side of a many-to-many relationship.");
    }/*from  w ww  . ja  va 2 s.c o  m*/

    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.getEntityBinding(entityName);

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

        boolean compositeIdProperty = isCompositeIdProperty(m, property.getInverseSide());
        if (!compositeIdProperty) {
            Backref prop = new Backref();
            final PersistentEntity owner = property.getOwner();
            prop.setEntityName(owner.getName());
            prop.setName(UNDERSCORE + addUnderscore(owner.getJavaClass().getSimpleName(), 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.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  av a 2  s  .  com*/
        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.grails.orm.hibernate.cfg.GrailsDomainBinder.java

License:Apache License

protected void bindCollectionWithJoinTable(ToMany property, InFlightMetadataCollector mappings,
        Collection collection, PropertyConfig config, String sessionFactoryBeanName) {

    NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName);

    SimpleValue element;/*from   ww  w  .  ja va 2s  .c  om*/
    final boolean isBasicCollectionType = property instanceof Basic;
    if (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 (isBasicCollectionType) {
        final Class<?> referencedType = ((Basic) property).getComponentType();
        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.getOwner()));
            if (typeName == null) {
                Type type = mappings.getTypeResolver().basic(className);
                if (type != null) {
                    typeName = type.getName();
                }
            }
            if (typeName == null) {
                String domainName = property.getOwner().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(property, getColumnForSimpleValue(element),
                        config.getJoinTable().getColumn());
            }
        }
    } else {
        final PersistentEntity domainClass = property.getAssociatedEntity();

        Mapping m = getMapping(domainClass);
        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(NameUtils.decapitalize(domainClass.getName()))
                        + FOREIGN_KEY_SUFFIX;
            }

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

    collection.setElement(element);

    bindCollectionForPropertyConfig(collection, config);
}

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

License:Apache License

protected void bindIdentity(HibernatePersistentEntity domainClass, RootClass root,
        InFlightMetadataCollector mappings, Mapping gormMapping, String sessionFactoryBeanName) {

    PersistentProperty identifierProp = domainClass.getIdentity();
    if (gormMapping == null) {
        if (identifierProp != null) {
            bindSimpleId(identifierProp, root, mappings, null, sessionFactoryBeanName);
        }/*from w w w.  j a  va2s  .co m*/
        return;
    }

    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) {
            PersistentProperty 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.grails.orm.hibernate.cfg.GrailsDomainBinder.java

License:Apache License

protected void bindCompositeId(PersistentEntity domainClass, RootClass root,
        CompositeIdentity compositeIdentity, InFlightMetadataCollector mappings,
        String sessionFactoryBeanName) {
    HibernatePersistentEntity hibernatePersistentEntity = (HibernatePersistentEntity) domainClass;
    Component id = new Component(mappings, root);
    id.setNullValue("undefined");
    root.setIdentifier(id);//from  w  w w. j a v a 2  s .  c  o  m
    root.setEmbeddedIdentifier(true);
    id.setComponentClassName(domainClass.getName());
    id.setKey(true);
    id.setEmbedded(true);

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

    id.setRoleName(path);

    final PersistentProperty[] composite = hibernatePersistentEntity.getCompositeIdentity();
    for (PersistentProperty property : composite) {
        if (property == null) {
            throw new MappingException("Property referenced in composite-id mapping of class ["
                    + domainClass.getName() + "] is not a valid property!");
        }

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

From source file:org.grails.orm.hibernate.cfg.GrailsDomainBinder.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
 *///from w w w  .  ja  va 2s.co  m
protected void createClassProperties(HibernatePersistentEntity domainClass, PersistentClass persistentClass,
        InFlightMetadataCollector mappings, String sessionFactoryBeanName) {

    final List<PersistentProperty> persistentProperties = domainClass.getPersistentProperties();
    Table table = persistentClass.getTable();

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

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

    List<Embedded> embedded = new ArrayList<>();

    for (PersistentProperty currentGrailsProp : persistentProperties) {

        // if its inherited skip
        if (currentGrailsProp.isInherited()) {
            continue;
        }
        if (currentGrailsProp.getName().equals(GormProperties.VERSION))
            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.isNullable(),
                        getColumnNameForPropertyAndPath(currentGrailsProp, EMPTY_PATH, null,
                                sessionFactoryBeanName),
                        mappings);
            } else {
                // create collection
                Collection collection = collectionType.create((ToMany) currentGrailsProp, persistentClass,
                        EMPTY_PATH, mappings, sessionFactoryBeanName);
                mappings.addCollectionBinding(collection);
                value = collection;
            }
        } else if (currentGrailsProp.getType().isEnum()) {
            value = new SimpleValue(mappings, table);
            bindEnumType(currentGrailsProp, (SimpleValue) value, EMPTY_PATH, sessionFactoryBeanName);
        } else if (currentGrailsProp instanceof Association) {
            Association association = (Association) currentGrailsProp;
            if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.ManyToOne) {
                if (LOG.isDebugEnabled())
                    LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                            + "] as ManyToOne");

                value = new ManyToOne(mappings, table);
                bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings,
                        sessionFactoryBeanName);
            } else if (currentGrailsProp instanceof org.grails.datastore.mapping.model.types.OneToOne
                    && userType == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName()
                            + "] as OneToOne");
                }

                final boolean isHasOne = isHasOne(association);
                if (isHasOne && !association.isBidirectional()) {
                    throw new MappingException("hasOne property [" + currentGrailsProp.getOwner().getName()
                            + "." + currentGrailsProp.getName()
                            + "] is not bidirectional. Specify the other side of the relationship!");
                } else if (canBindOneToOneWithSingleColumnAndForeignKey((Association) currentGrailsProp)) {
                    value = new OneToOne(mappings, table, persistentClass);
                    bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp,
                            (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName);
                } else {
                    if (isHasOne && association.isBidirectional()) {
                        value = new OneToOne(mappings, table, persistentClass);
                        bindOneToOne((org.grails.datastore.mapping.model.types.OneToOne) currentGrailsProp,
                                (OneToOne) value, EMPTY_PATH, sessionFactoryBeanName);
                    } else {
                        value = new ManyToOne(mappings, table);
                        bindManyToOne((Association) currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings,
                                sessionFactoryBeanName);
                    }
                }
            } else if (currentGrailsProp instanceof Embedded) {
                embedded.add((Embedded) currentGrailsProp);
                continue;
            }
        }
        // work out what type of relationship it is and bind value
        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);
        }
    }

    for (Embedded association : embedded) {
        Value value = new Component(mappings, persistentClass);

        bindComponent((Component) value, association, true, mappings, sessionFactoryBeanName);
        Property property = createProperty(value, persistentClass, association, mappings);
        persistentClass.addProperty(property);
    }
    bindNaturalIdentifier(table, gormMapping, persistentClass);
}

From source file:org.openbravo.dal.core.OBTuplizer.java

License:Open Source License

@Override
protected ProxyFactory buildProxyFactory(PersistentClass thePersistentClass, Getter idGetter, Setter idSetter) {
    final Class<?> mappedClass = thePersistentClass.getMappedClass();
    Check.isNotNull(mappedClass, "Mapped class of entity " + thePersistentClass.getEntityName() + " is null");

    // determine the id getter and setter methods from the proxy interface
    // (if/*from   w  ww.ja v a2s .com*/
    // any)
    // determine all interfaces needed by the resulting proxy
    final HashSet<Object> proxyInterfaces = new HashSet<Object>();
    proxyInterfaces.add(HibernateProxy.class);

    final Class<?> proxyInterface = thePersistentClass.getProxyInterface();

    if (proxyInterface != null && !mappedClass.equals(proxyInterface)) {
        if (!proxyInterface.isInterface()) {
            throw new MappingException(
                    "proxy must be either an interface, or the class itself: " + getEntityName());
        }
        proxyInterfaces.add(proxyInterface);
    }

    if (mappedClass.isInterface()) {
        proxyInterfaces.add(mappedClass);
    }

    final Iterator<?> iter = thePersistentClass.getSubclassIterator();
    while (iter.hasNext()) {
        final Subclass subclass = (Subclass) iter.next();
        final Class<?> subclassProxy = subclass.getProxyInterface();
        final Class<?> subclassClass = subclass.getMappedClass();
        if (subclassProxy != null && !subclassClass.equals(subclassProxy)) {
            if (proxyInterface == null || !proxyInterface.isInterface()) {
                throw new MappingException(
                        "proxy must be either an interface, or the class itself: " + subclass.getEntityName());
            }
            proxyInterfaces.add(subclassProxy);
        }
    }

    final Method idGetterMethod = idGetter == null ? null : idGetter.getMethod();
    final Method idSetterMethod = idSetter == null ? null : idSetter.getMethod();

    final Method proxyGetIdentifierMethod = idGetterMethod == null || proxyInterface == null ? null
            : ReflectHelper.getMethod(proxyInterface, idGetterMethod);
    final Method proxySetIdentifierMethod = idSetterMethod == null || proxyInterface == null ? null
            : ReflectHelper.getMethod(proxyInterface, idSetterMethod);

    ProxyFactory pf = buildProxyFactoryInternal(thePersistentClass, idGetter, idSetter);
    try {
        pf.postInstantiate(getEntityName(), mappedClass, proxyInterfaces, proxyGetIdentifierMethod,
                proxySetIdentifierMethod,
                thePersistentClass.hasEmbeddedIdentifier()
                        ? (CompositeType) thePersistentClass.getIdentifier().getType()
                        : null);
    } catch (final HibernateException he) {
        log.warn("could not create proxy factory for:" + getEntityName(), he);
        pf = null;
    }
    return pf;
}

From source file:org.openmrs.api.db.hibernate.NativeIfNotAssignedIdentityGenerator.java

License:Mozilla Public License

/**
 * @see org.hibernate.id.Configurable#configure(org.hibernate.type.Type, java.util.Properties,
 *      org.hibernate.dialect.Dialect)/*w  w w .j a v  a 2  s . com*/
 */
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
    this.entityName = params.getProperty(ENTITY_NAME);
    if (entityName == null) {
        throw new MappingException("no entity name");
    }
}