Example usage for org.hibernate.mapping Collection getElement

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

Introduction

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

Prototype

public Value getElement() 

Source Link

Usage

From source file:com.mysema.query.jpa.codegen.HibernateDomainExporter.java

License:Apache License

private void handleProperty(EntityType entityType, Class<?> cl, org.hibernate.mapping.Property p)
        throws NoSuchMethodException, ClassNotFoundException {
    if (p.isBackRef()) {
        return;/*from   www  .ja v  a2 s  .com*/
    }
    Class<?> clazz = Object.class;
    try {
        clazz = p.getType().getReturnedClass();
    } catch (MappingException e) {
        // ignore
    }
    Type propertyType = getType(cl, clazz, p.getName());
    if (p.isComposite()) {
        EntityType embeddedType = createEmbeddableType(propertyType);
        Iterator<?> properties = ((Component) p.getValue()).getPropertyIterator();
        while (properties.hasNext()) {
            handleProperty(embeddedType, embeddedType.getJavaClass(),
                    (org.hibernate.mapping.Property) properties.next());
        }
        propertyType = embeddedType;
    } else if (propertyType.getCategory() == TypeCategory.ENTITY || p.getValue() instanceof ManyToOne) {
        propertyType = createEntityType(propertyType);
    } else if (propertyType.getCategory() == TypeCategory.CUSTOM) {
        propertyType = createEmbeddableType(propertyType);
    } else if (p.getValue() instanceof org.hibernate.mapping.Collection) {
        org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) p.getValue();
        if (collection.getElement() instanceof OneToMany) {
            String entityName = ((OneToMany) collection.getElement()).getReferencedEntityName();
            if (entityName != null) {
                Type componentType = typeFactory.create(Class.forName(entityName));
                propertyType = new SimpleType(propertyType, componentType);
            }
        } else if (collection.getElement() instanceof Component) {
            Component component = (Component) collection.getElement();
            Class<?> embeddedClass = Class.forName(component.getComponentClassName());
            EntityType embeddedType = createEmbeddableType(embeddedClass);
            Iterator<?> properties = component.getPropertyIterator();
            while (properties.hasNext()) {
                handleProperty(embeddedType, embeddedClass, (org.hibernate.mapping.Property) properties.next());
            }
        }
    }
    AnnotatedElement annotated = getAnnotatedElement(cl, p.getName());
    Property property = createProperty(entityType, p.getName(), propertyType, annotated);
    entityType.addProperty(property);
}

From source file:com.oy.shared.lm.ext.HBMCtoGRAPH.java

License:Open Source License

private void addCollectionProp(Property prop, GraphNode current) {
    Value val = prop.getValue();
    if (!(val instanceof Collection)) {
        throw new RuntimeException("Expected Collection.");
    }//  ww w  .j a va2 s.c om

    Collection col = (Collection) prop.getValue();
    Value elem = col.getElement();

    if (elem instanceof OneToMany) {
        String clazz = col.getElement().getType().getName();
        GraphNode child = getOrCreateNode(clazz);

        // relation         
        GraphEdge edge = graph.addEdge(current, child);
        edge.getInfo().setCaption(prop.getName());
        edge.getInfo().setLineColor(colors[2]);
        edge.getInfo().setHeadCaption("0..n");
        edge.getInfo().setArrowTailDiamond();

        return;
    }

    if (elem instanceof ManyToOne) {
        String clazz = col.getElement().getType().getName();
        GraphNode child = getOrCreateNode(clazz);

        // relation         
        GraphEdge edge = graph.addEdge(current, child);
        edge.getInfo().setCaption(prop.getName());
        edge.getInfo().setLineColor(colors[2]);
        edge.getInfo().setArrowTailDiamond();
        edge.getInfo().setHeadCaption("0..n");
        edge.getInfo().setTailCaption("0..n");
        return;
    }

    if (elem instanceof Component) {
        String clazz = prop.getName();
        GraphNode child = getOrCreateNode("<<" + col.getClass().getName() + ">>\n" + clazz);

        // relation         
        GraphEdge edge = graph.addEdge(current, child);
        edge.getInfo().setLineColor(colors[1]);
        edge.getInfo().setArrowTailDiamond();

        processProperties(((Component) elem).getPropertyIterator(), child);
        return;
    }

    if (elem instanceof SimpleValue) {
        String clazz = prop.getName();
        GraphNode child = getOrCreateNode("<<" + col.getClass().getName() + ">>\n" + clazz);

        // relation         
        GraphEdge edge = graph.addEdge(current, child);
        edge.getInfo().setLineColor(colors[1]);
        edge.getInfo().setArrowTailDiamond();

        List attrs = new ArrayList();
        Attribute attr = addSimpleProp((SimpleValue) elem, null);
        attrs.add(attr);
        String label = renderAttributes((Attribute[]) attrs.toArray(new Attribute[] {}));
        child.getInfo().setCaption(label);

        return;
    }

    throw new RuntimeException("Unexpected collection element.");
}

From source file:com.querydsl.jpa.codegen.HibernateDomainExporter.java

License:Apache License

private void handleProperty(EntityType entityType, Class<?> cl, org.hibernate.mapping.Property p)
        throws NoSuchMethodException, ClassNotFoundException {
    if (p.isBackRef()) {
        return;//from   w ww. j  a  v a2  s.  c  o m
    }
    Class<?> clazz = Object.class;
    try {
        clazz = p.getType().getReturnedClass();
    } catch (MappingException e) {
        // ignore
    }
    Type propertyType = getType(cl, clazz, p.getName());
    try {
        propertyType = getPropertyType(p, propertyType);
    } catch (MappingException e) {
        // ignore
    }

    AnnotatedElement annotated = getAnnotatedElement(cl, p.getName());
    propertyType = getTypeOverride(propertyType, annotated);
    if (propertyType == null) {
        return;
    }

    if (p.isComposite()) {
        EntityType embeddedType = createEmbeddableType(propertyType);
        Iterator<?> properties = ((Component) p.getValue()).getPropertyIterator();
        while (properties.hasNext()) {
            handleProperty(embeddedType, embeddedType.getJavaClass(),
                    (org.hibernate.mapping.Property) properties.next());
        }
        propertyType = embeddedType;
    } else if (propertyType.getCategory() == TypeCategory.ENTITY || p.getValue() instanceof ManyToOne) {
        propertyType = createEntityType(propertyType);
    } else if (propertyType.getCategory() == TypeCategory.CUSTOM) {
        propertyType = createEmbeddableType(propertyType);
    } else if (p.getValue() instanceof org.hibernate.mapping.Collection) {
        org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) p.getValue();
        if (collection.getElement() instanceof OneToMany) {
            String entityName = ((OneToMany) collection.getElement()).getReferencedEntityName();
            if (entityName != null) {
                if (collection.isMap()) {
                    Type keyType = typeFactory
                            .get(Class.forName(propertyType.getParameters().get(0).getFullName()));
                    Type valueType = typeFactory.get(Class.forName(entityName));
                    propertyType = new SimpleType(propertyType,
                            normalize(propertyType.getParameters().get(0), keyType),
                            normalize(propertyType.getParameters().get(1), valueType));
                } else {
                    Type componentType = typeFactory.get(Class.forName(entityName));
                    propertyType = new SimpleType(propertyType,
                            normalize(propertyType.getParameters().get(0), componentType));
                }
            }
        } else if (collection.getElement() instanceof Component) {
            Component component = (Component) collection.getElement();
            Class<?> embeddedClass = Class.forName(component.getComponentClassName());
            EntityType embeddedType = createEmbeddableType(embeddedClass);
            Iterator<?> properties = component.getPropertyIterator();
            while (properties.hasNext()) {
                handleProperty(embeddedType, embeddedClass, (org.hibernate.mapping.Property) properties.next());
            }
        }
    }

    Property property = createProperty(entityType, p.getName(), propertyType, annotated);
    entityType.addProperty(property);
}

From source file:com.vecna.maven.hibernate.HibernateDocMojo.java

License:Apache License

/**
 * Populate Hibernate properties with comments from javadocs (including nested properties).
 * @param propertyIterator iterator over top-level properties
 * @param accumulatedJavadoc comments accumulated so far (for nested properties)
 *///from w w w .  j  a  v a2  s. c  om
private void processProperties(Iterator<Property> propertyIterator, Class<?> cls, JavaDocBuilder javaDocs,
        String accumulatedJavadoc) {
    JavaClass javaClass = javaDocs.getClassByName(cls.getName());

    if (javaClass != null) {
        while (propertyIterator.hasNext()) {
            Property prop = propertyIterator.next();

            Value value = prop.getValue();

            if (value instanceof Collection) {
                Collection collection = (Collection) value;

                Value elementValue = collection.getElement();

                if (elementValue instanceof Component) {
                    processComponent((Component) elementValue, javaDocs, accumulatedJavadoc);
                }

                Table collectionTable = collection.getCollectionTable();

                if (collectionTable.getComment() == null) {
                    collectionTable.setComment(getSimpleValueJavadoc(prop, cls, javaClass));
                }
            } else if (value instanceof Component) {
                String comment = getSimpleValueJavadoc(prop, cls, javaClass);
                comment = accumulateJavadoc(comment, accumulatedJavadoc);
                processComponent((Component) value, javaDocs, comment);
            } else if (value instanceof SimpleValue) {
                String comment = getSimpleValueJavadoc(prop, cls, javaClass);
                comment = accumulateJavadoc(comment, accumulatedJavadoc);
                setComment(comment, prop);
            }
        }

    }
}

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

License:BSD License

/**
 * This Function finds all the relations in i.e Many-To-Many and One-To-Many
 * All the relations are kept in HashMap where key is formed as table1@table2@table_name@attributeName
 * and value is Many-To-Many or One-To-Many
 *
 * @return Map//  w  ww.  j a v a 2 s  .c  o  m
 */
private static void findRelations() {
    try {
        Iterator itr1 = cfg.getCollectionMappings();

        while (itr1.hasNext()) {
            Collection col = (Collection) itr1.next();

            if (col.getElement().getClass().getName().equals(ManyToOne.class.getName())) {
                saveRelations(col, "ManyToMany");
            } else {
                saveRelations(col, "OneToMany");
            }
        }
    } catch (Exception e) {
        //This line is commented because logger when not initialized properly throws NullPointerException
        //Logger.out.info("Error occured in fildAllRelations Function:"+e);
    }

}

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

License:BSD License

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

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

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

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

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

License:BSD License

/** This function returns the role Id
 * from hibernate mapping and returns the value
 * @param attributeName/*from   w w w  .j  a v  a  2 s. c  o  m*/
 * @return roleKeyId
 *
 */
public static String getRoleKeyId(String attributeName) {
    org.hibernate.mapping.Collection col1 = cfg.getCollectionMapping(attributeName);
    Iterator colIt = col1.getElement().getColumnIterator();
    while (colIt.hasNext()) {
        Column col = (Column) colIt.next();
        return (col.getName());
    }
    return "";
}

From source file:net.chrisrichardson.ormunit.hibernate.ComponentCollectionFieldMapping.java

License:Apache License

public ComponentCollectionFieldMapping(Property property, Collection value) {
    this.property = property;
    this.value = value;
    this.componentMapping = new ComponentFieldMapping(property, (Component) value.getElement());
}

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

License:Open Source License

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

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

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

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

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

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

License:Apache License

protected void bindCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings,
        Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) {

    PersistentClass associatedClass = null;

    if (LOG.isDebugEnabled())
        LOG.debug("Mapping collection: " + collection.getRole() + " -> "
                + collection.getCollectionTable().getName());

    PropertyConfig propConfig = getPropertyConfig(property);

    if (propConfig != null && StringUtils.hasText(propConfig.getSort())) {
        if (!property.isBidirectional() && property.isOneToMany()) {
            throw new GrailsDomainException("Default sort for associations ["
                    + property.getDomainClass().getName() + "->" + property.getName()
                    + "] are not supported with unidirectional one to many relationships.");
        }//from   ww w  .  j a v  a  2  s  .co  m
        GrailsDomainClass referenced = property.getReferencedDomainClass();
        if (referenced != null) {
            GrailsDomainClassProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());

            String associatedClassName = property.getReferencedDomainClass().getFullName();

            associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
            if (associatedClass != null) {
                collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass,
                        collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
            }
        }
    }

    // Configure one-to-many
    if (collection.isOneToMany()) {

        GrailsDomainClass referenced = property.getReferencedDomainClass();
        Mapping m = getRootMapping(referenced);
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();

        if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
            Mapping rootMapping = getRootMapping(referenced);
            String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;

            if (rootMapping != null) {
                final ColumnConfig discriminatorColumn = rootMapping.getDiscriminatorColumn();
                if (discriminatorColumn != null) {
                    discriminatorColumnName = discriminatorColumn.getName();
                }
                if (rootMapping.getDiscriminatorMap().get("formula") != null) {
                    discriminatorColumnName = (String) m.getDiscriminatorMap().get("formula");
                }
            }
            //NOTE: this will build the set for the in clause if it has sublcasses
            Set<String> discSet = buildDiscriminatorSet(referenced);
            String inclause = 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);
    }
}