Example usage for org.hibernate.mapping PersistentClass addProperty

List of usage examples for org.hibernate.mapping PersistentClass addProperty

Introduction

In this page you can find the example usage for org.hibernate.mapping PersistentClass addProperty.

Prototype

@Override
    public void addProperty(Property p) 

Source Link

Usage

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

License:Open Source License

protected void createO2M(Configuration config, Mappings mappings, ForeignKey relationship) {

    com.manydesigns.portofino.model.database.Table manyMDTable = relationship.getFromTable();
    com.manydesigns.portofino.model.database.Table oneMDTable = relationship.getToTable();

    //Se la classe One non e' dinamica e
    // non ha la proprieta' non inserisco la relazione
    if (oneMDTable.getJavaClass() != null) {
        try {//  www.  j  a  v  a  2s . c o  m
            Class oneClass = oneMDTable.getActualJavaClass();
            JavaClassAccessor accessor = JavaClassAccessor.getClassAccessor(oneClass);
            PropertyAccessor[] propertyAccessors = accessor.getProperties();
            boolean found = false;
            for (PropertyAccessor propertyAccessor : propertyAccessors) {
                if (propertyAccessor.getName().equals(relationship.getActualManyPropertyName())) {
                    found = true;
                }
            }
            if (!found) {
                logger.warn("Property '{}' not found, skipping relationship {}",
                        relationship.getActualManyPropertyName(), relationship.getQualifiedName());
                return;
            }
        } catch (Exception e) {
            //se non c'e' non inserisco la relazione
            logger.warn("Property not found, skipping relationship ", e);
            return;
        }
    }
    //relazione virtuali fra Database differenti
    if (!manyMDTable.getDatabaseName().equalsIgnoreCase(oneMDTable.getDatabaseName())) {
        logger.warn("Relationship crosses databases, skipping: {}", relationship.getQualifiedName());
        return;
    }

    String manyMDQualifiedTableName = manyMDTable.getActualEntityName();
    String oneMDQualifiedTableName = oneMDTable.getActualEntityName();

    PersistentClass clazzOne = config.getClassMapping(oneMDQualifiedTableName);
    if (clazzOne == null) {
        logger.error("Cannot find table '{}' as 'one' side of foreign key '{}'. Skipping relationship.",
                oneMDQualifiedTableName, relationship.getName());
        return;
    }

    PersistentClass clazzMany = config.getClassMapping(manyMDQualifiedTableName);
    if (clazzMany == null) {
        logger.error("Cannot find table '{}' as 'many' side of foreign key '{}'. Skipping relationship.",
                manyMDQualifiedTableName, relationship.getName());
        return;
    }

    //Uso i Bag perche' i set non funzionano con i componenti dinamici
    Bag set = new Bag(mappings, clazzOne);
    // Mettere Lazy in debug a false per ottenere subito eventuali errori
    // nelle relazioni
    set.setLazy(LAZY);

    set.setRole(
            relationship.getToTable().getActualEntityName() + "." + relationship.getActualManyPropertyName());
    //set.setNodeName(relationship.getActualManyPropertyName());
    set.setCollectionTable(clazzMany.getTable());
    OneToMany oneToMany = new OneToMany(mappings, set.getOwner());
    set.setElement(oneToMany);

    oneToMany.setReferencedEntityName(manyMDQualifiedTableName);

    oneToMany.setAssociatedClass(clazzMany);
    oneToMany.setEmbedded(true);

    set.setSorted(false);
    set.setFetchMode(FetchMode.DEFAULT);
    //Riferimenti alle colonne

    DependantValue dv;
    Table tableMany = clazzMany.getTable();
    Table tableOne = clazzOne.getTable();
    List<Column> oneColumns = new ArrayList<Column>();
    List<Column> manyColumns = new ArrayList<Column>();
    //Chiave multipla
    final List<Reference> refs = relationship.getReferences();
    if (refs.size() > 1) {
        dv = createFKComposite(mappings, relationship, manyMDTable, clazzOne, clazzMany, set, tableMany,
                tableOne, oneColumns, manyColumns);
    } else { //chiave straniera singola
        dv = createFKSingle(mappings, clazzOne, clazzMany, tableOne, oneColumns, manyColumns, refs);
    }

    tableMany.createForeignKey(relationship.getName(), manyColumns, oneMDQualifiedTableName, oneColumns);

    dv.setNullable(false);
    set.setKey(dv);
    mappings.addCollection(set);

    Property prop = new Property();
    prop.setName(relationship.getActualManyPropertyName());
    //prop.setNodeName(relationship.getActualManyPropertyName());
    prop.setValue(set);
    if (ForeignKeyConstraintType.importedKeyCascade.name().equalsIgnoreCase(relationship.getOnDelete())) {
        prop.setCascade("delete");
    } else {
        prop.setCascade("none");
    }
    clazzOne.addProperty(prop);

    //if(!StringUtils.)
}

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

License:Open Source License

public static void merge(PersistentClass sub, PersistentClass parent) {
    if (!mergeSupport)
        throw new RuntimeException("Merge not supported!");

    String className = sub.getClassName();
    // 1. convert old to mapped superclass
    MappedSuperclass msc = new MappedSuperclass(parent.getSuperMappedSuperclass(), null);
    final Class<?> parentClass = parent.getMappedClass();
    msc.setMappedClass(parentClass);//from w  w  w . j av a  2s  .c o  m

    // 2.clear old subclass property
    parent.setSuperMappedSuperclass(msc);
    parent.setClassName(className);
    parent.setProxyInterfaceName(className);
    if (parent instanceof RootClass) {
        if (!parentClass.getSuperclass().isAnnotationPresent(Entity.class)) {
            ((RootClass) parent).setDiscriminator(null);
            ((RootClass) parent).setPolymorphic(false);
            @SuppressWarnings("unchecked")
            Iterator<Column> iter = parent.getTable().getColumnIterator();
            while (iter.hasNext()) {
                if (iter.next().getName().equalsIgnoreCase("dtype")) {
                    iter.remove();
                    break;
                }
            }
        }
    }

    try {
        @SuppressWarnings("unchecked")
        List<Property> declareProperties = (List<Property>) declarePropertyField.get(parent);
        for (Property p : declareProperties)
            msc.addDeclaredProperty(p);
        ((List<?>) subPropertyField.get(parent)).clear();
        ((List<?>) subclassField.get(parent)).clear();
    } catch (Exception e) {
    }

    // 3. add property to old
    try {
        Iterator<?> pIter = sub.getPropertyIterator();
        while (pIter.hasNext()) {
            Property p = (Property) pIter.next();
            parent.addProperty(p);
        }
    } catch (Exception e) {
    }
    logger.info("{} replace {}.", sub.getClassName(), parent.getClassName());
}

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()//w w  w .  j a va2s  . com
                + "]. 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

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

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

    referenced.addProperty(prop);
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.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
 *///from w ww .  j a v  a  2 s . 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 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);

    SimpleValue iv = new SimpleValue(mappings, list.getCollectionTable());
    bindSimpleValue("integer", iv, true, columnName, mappings);
    iv.setTypeName("integer");
    list.setIndex(iv);//from   ww  w  .ja va 2s  .c  om
    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);

        final boolean isManyToMany = property.isManyToMany();
        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.GrailsDomainBinder.java

License:Apache License

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

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

    referenced.addProperty(prop);
}

From source file:org.codehaus.groovy.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 www  . j a v a2s.  c  o  m*/
protected static void createClassProperties(GrailsDomainClass domainClass, PersistentClass persistentClass,
        Mappings mappings, String sessionFactoryBeanName) {

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

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

    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 = CollectionType.collectionTypeForClass(currentGrailsProp.getType());

        Class<?> userType = getUserType(currentGrailsProp);

        if (collectionType != null) {
            String typeName = getTypeName(currentGrailsProp, getPropertyConfig(currentGrailsProp), gormMapping);
            if (typeName != null && "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.eclipse.emf.teneo.hibernate.HbDataStore.java

License:Open Source License

/**
 * Extra lazy mapping for lists needs a real property for the list index and
 * a real inverse for the other side as well.
 * // w w  w.  ja  v  a 2s. com
 * This method iterates over all associations and adds an inverse for the
 * list and set mappings.
 */
protected void addExtraLazyInverseProperties() {
    final Map<String, PersistentClass> persistentClasses = new HashMap<String, PersistentClass>();
    for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) {
        final PersistentClass pc = (PersistentClass) pcs.next();
        if (isClassOrSuperClassEAVMapped(pc)) {
            continue;
        }
        persistentClasses.put(pc.getEntityName(), pc);
    }
    for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) {
        final PersistentClass pc = (PersistentClass) pcs.next();

        // copy to prevent concurrent modification
        final Iterator<?> propIt = pc.getPropertyIterator();
        final List<Property> props = new ArrayList<Property>();
        while (propIt.hasNext()) {
            final Property prop = (Property) propIt.next();
            props.add(prop);
        }

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

            final EStructuralFeature ef = eClass == null ? null
                    : StoreUtil.getEStructuralFeature(eClass, prop.getName());
            if (ef != null && ef instanceof EReference && prop.getValue() instanceof Collection) {
                final Collection collection = (Collection) prop.getValue();
                final EReference eReference = (EReference) ef;

                // only work for extra lazy
                if (!collection.isExtraLazy()) {
                    continue;
                }

                final Value elementValue = collection.getElement();
                final PersistentClass elementPC;
                if (elementValue instanceof OneToMany) {
                    final OneToMany oneToMany = (OneToMany) elementValue;
                    elementPC = oneToMany.getAssociatedClass();
                } else if (elementValue instanceof ManyToOne) {
                    final ManyToOne mto = (ManyToOne) elementValue;
                    elementPC = persistentClasses.get(mto.getReferencedEntityName());
                } else {
                    continue;
                }

                if (isClassOrSuperClassEAVMapped(elementPC)) {
                    continue;
                }

                collection.setInverse(true);

                // and add an eopposite
                if (eReference.getEOpposite() == null) {

                    final Table collectionTable = collection.getCollectionTable();

                    if (isClassOrSuperClassEAVMapped(elementPC)) {
                        continue;
                    }

                    final Property inverseRefProperty = new Property();
                    inverseRefProperty.setName(StoreUtil.getExtraLazyInversePropertyName(ef));
                    final Map<Object, Object> metas = new HashMap<Object, Object>();
                    final MetaAttribute metaAttribute = new MetaAttribute(
                            HbConstants.SYNTHETIC_PROPERTY_INDICATOR);
                    metaAttribute.addValue("true");
                    metas.put(HbConstants.SYNTHETIC_PROPERTY_INDICATOR, metaAttribute);
                    inverseRefProperty.setMetaAttributes(metas);
                    inverseRefProperty.setNodeName(inverseRefProperty.getName());
                    inverseRefProperty.setPropertyAccessorName(SyntheticPropertyHandler.class.getName());
                    inverseRefProperty.setLazy(false);

                    final ManyToOne mto = new ManyToOne(getMappings(), collectionTable);
                    mto.setReferencedEntityName(pc.getEntityName());
                    mto.setLazy(false);
                    mto.setFetchMode(FetchMode.SELECT);

                    inverseRefProperty.setValue(mto);
                    final Iterator<?> it = collection.getKey().getColumnIterator();
                    while (it.hasNext()) {
                        final Column originalColumn = (Column) it.next();
                        // final Column newColumn = new
                        // Column(originalColumn.getName());
                        mto.addColumn(originalColumn);
                    }
                    mto.createForeignKey();

                    // now determine if a join should be created
                    if (collectionTable.getName().equalsIgnoreCase(elementPC.getTable().getName())) {
                        elementPC.addProperty(inverseRefProperty);
                    } else {
                        // create a join
                        final Join join = new Join();
                        join.setPersistentClass(elementPC);
                        join.setTable(collectionTable);
                        join.addProperty(inverseRefProperty);

                        final ManyToOne keyValue = new ManyToOne(getMappings(), collectionTable);
                        join.setKey(keyValue);
                        @SuppressWarnings("unchecked")
                        final Iterator<Column> keyColumns = collection.getElement().getColumnIterator();
                        while (keyColumns.hasNext()) {
                            keyValue.addColumn(keyColumns.next());
                        }
                        keyValue.setReferencedEntityName(elementPC.getEntityName());
                        keyValue.setTable(collectionTable);
                        keyValue.createForeignKey();

                        elementPC.addJoin(join);
                    }
                }

                // add an opposite index
                if (collection.isIndexed() && !collection.isMap()) {

                    Table collectionTable = collection.getCollectionTable();

                    IndexedCollection indexedCollection = (IndexedCollection) collection;

                    final Column column = (Column) indexedCollection.getIndex().getColumnIterator().next();

                    final Property indexProperty = new Property();
                    indexProperty.setName(StoreUtil.getExtraLazyInverseIndexPropertyName(ef));
                    final Map<Object, Object> metas = new HashMap<Object, Object>();
                    final MetaAttribute metaAttribute = new MetaAttribute(
                            HbConstants.SYNTHETIC_PROPERTY_INDICATOR);
                    metaAttribute.addValue("true");
                    metas.put(HbConstants.SYNTHETIC_PROPERTY_INDICATOR, metaAttribute);
                    indexProperty.setMetaAttributes(metas);
                    indexProperty.setNodeName(indexProperty.getName());
                    indexProperty.setPropertyAccessorName(SyntheticPropertyHandler.class.getName());
                    // always make this nullable, nullability is controlled
                    // by the main property
                    indexProperty.setOptional(true);

                    Join join = null;
                    @SuppressWarnings("unchecked")
                    final Iterator<Join> it = (Iterator<Join>) elementPC.getJoinIterator();
                    while (it.hasNext()) {
                        final Join foundJoin = it.next();
                        if (foundJoin.getTable().getName().equalsIgnoreCase(collectionTable.getName())) {
                            join = foundJoin;
                            collectionTable = join.getTable();
                            break;
                        }
                    }

                    final SimpleValue sv = new SimpleValue(getMappings(),
                            indexedCollection.getIndex().getTable());
                    sv.setTypeName("integer");
                    // final Column svColumn = new Column(column.getName());
                    sv.addColumn(column); // checkColumnExists(collectionTable,
                    // svColumn));
                    indexProperty.setValue(sv);
                    if (join != null) {
                        join.addProperty(indexProperty);
                    } else {
                        elementPC.addProperty(indexProperty);
                    }
                }
            }
        }
    }

}

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

License:Open Source License

protected void addContainerMappingToPC(PersistentClass pc) {
    if (log.isDebugEnabled()) {
        log.debug("Adding eContainer and econtainerfeatureid properties to " + pc.getClassName());
    }//from  w  w  w  .j a v a 2s  . c o  m
    final EContainerFeaturePersistenceStrategy featurePersistenceStrategy = getPersistenceOptions()
            .getEContainerFeaturePersistenceStrategy();

    final Property eContainer = new Property();
    eContainer.setName(HbConstants.PROPERTY_ECONTAINER);
    eContainer.setMetaAttributes(new HashMap<Object, Object>());
    eContainer.setNodeName(eContainer.getName());
    eContainer.setPropertyAccessorName(EContainerAccessor.class.getName());

    final SimpleValue sv = new SimpleValue(getMappings(), pc.getTable());
    sv.setTypeName(EContainerUserType.class.getName());

    final Column eccColumn = new Column(getPersistenceOptions().getSQLColumnNamePrefix()
            + getPersistenceOptions().getEContainerClassColumn());
    sv.addColumn(checkColumnExists(pc.getTable(), eccColumn));

    final Column ecColumn = new Column(
            getPersistenceOptions().getSQLColumnNamePrefix() + getPersistenceOptions().getEContainerColumn());
    sv.addColumn(checkColumnExists(pc.getTable(), ecColumn));

    eContainer.setValue(sv);
    pc.addProperty(eContainer);

    if (featurePersistenceStrategy.equals(EContainerFeaturePersistenceStrategy.FEATUREID)
            || featurePersistenceStrategy.equals(EContainerFeaturePersistenceStrategy.BOTH)) {
        final Property ecFID = new Property();
        ecFID.setName(HbConstants.PROPERTY_ECONTAINER_FEATURE_ID);
        ecFID.setMetaAttributes(new HashMap<Object, Object>());
        ecFID.setNodeName(ecFID.getName());
        ecFID.setPropertyAccessorName(EContainerFeatureIDAccessor.class.getName());
        final SimpleValue svfid = new SimpleValue(getMappings(), pc.getTable());
        svfid.setTypeName("integer");

        final Column ecfColumn = new Column(
                getPersistenceOptions().getSQLColumnNamePrefix() + HbConstants.COLUMN_ECONTAINER_FEATUREID);
        svfid.addColumn(checkColumnExists(pc.getTable(), ecfColumn));

        ecFID.setValue(svfid);
        pc.addProperty(ecFID);
    }
    if (featurePersistenceStrategy.equals(EContainerFeaturePersistenceStrategy.FEATURENAME)
            || featurePersistenceStrategy.equals(EContainerFeaturePersistenceStrategy.BOTH)) {
        final Property ecFID = new Property();
        ecFID.setName(HbConstants.PROPERTY_ECONTAINER_FEATURE_NAME);
        ecFID.setMetaAttributes(new HashMap<Object, Object>());
        ecFID.setNodeName(ecFID.getName());
        ecFID.setPropertyAccessorName(NewEContainerFeatureIDPropertyHandler.class.getName());
        final SimpleValue svfid = new SimpleValue(getMappings(), pc.getTable());
        svfid.setTypeName(EContainerFeatureIDUserType.class.getName());

        final Column ecfColumn = new Column(getPersistenceOptions().getSQLColumnNamePrefix()
                + getPersistenceOptions().getEContainerFeatureNameColumn());

        ecfColumn.setLength(getEContainerFeatureNameColumnLength());

        svfid.addColumn(checkColumnExists(pc.getTable(), ecfColumn));

        ecFID.setValue(svfid);
        pc.addProperty(ecFID);
    }
}