Example usage for org.hibernate.mapping Collection getOwner

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

Introduction

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

Prototype

public PersistentClass getOwner() 

Source Link

Usage

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

License:Open Source License

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

    return false;
}

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

License:Open Source License

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

    return false;
}

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  w  w .  j av  a  2 s  .c  o  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:org.beangle.orm.hibernate.tool.DdlGenerator.java

License:Open Source License

/**
 * Generate sql scripts/*  ww  w.  ja  v  a 2  s .  co 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

/**
 * Creates the DependentValue object that forms a primary key reference for the collection.
 *
 * @param mappings//from w w w . j a  v a  2s .  c om
 * @param property          The grails property
 * @param collection        The collection object
 * @param persistentClasses
 * @return The DependantValue (key)
 */
protected DependantValue createPrimaryKeyValue(Mappings mappings, GrailsDomainClassProperty property,
        Collection collection, Map<?, ?> persistentClasses) {
    KeyValue keyValue;
    DependantValue key;
    String propertyRef = collection.getReferencedPropertyName();
    // this is to support mapping by a property
    if (propertyRef == null) {
        keyValue = collection.getOwner().getIdentifier();
    } else {
        keyValue = (KeyValue) collection.getOwner().getProperty(propertyRef).getValue();
    }

    if (LOG.isDebugEnabled())
        LOG.debug("[GrailsDomainBinder] creating dependant key value  to table ["
                + keyValue.getTable().getName() + "]");

    key = new DependantValue(mappings, collection.getCollectionTable(), keyValue);

    key.setTypeName(null);
    // make nullable and non-updateable
    key.setNullable(true);
    key.setUpdateable(false);
    return key;
}

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

License:Apache License

/**
 * First pass to bind collection to Hibernate metamodel, sets up second pass
 *
 * @param property   The GrailsDomainClassProperty instance
 * @param collection The collection//from w ww . j  a  v  a 2 s  . c  om
 * @param owner      The owning persistent class
 * @param mappings   The Hibernate mappings instance
 * @param path
 */
protected void bindCollection(GrailsDomainClassProperty property, Collection collection, PersistentClass owner,
        Mappings mappings, String path, String sessionFactoryBeanName) {

    // set role
    String propertyName = getNameForPropertyAndPath(property, path);
    collection.setRole(qualify(property.getDomainClass().getFullName(), propertyName));

    PropertyConfig pc = getPropertyConfig(property);
    // configure eager fetching
    if (property.getFetchMode() == GrailsDomainClassProperty.FETCH_EAGER) {
        collection.setFetchMode(FetchMode.JOIN);
    } else if (pc != null && pc.getFetch() != null) {
        collection.setFetchMode(pc.getFetch());
    } else {
        collection.setFetchMode(FetchMode.DEFAULT);
    }

    if (pc != null && pc.getCascade() != null) {
        collection.setOrphanDelete(pc.getCascade().equals(CASCADE_ALL_DELETE_ORPHAN));
    }
    // if it's a one-to-many mapping
    if (shouldBindCollectionWithForeignKey(property)) {
        OneToMany oneToMany = new OneToMany(mappings, collection.getOwner());
        collection.setElement(oneToMany);
        bindOneToMany(property, oneToMany, mappings);
    } else {
        bindCollectionTable(property, mappings, collection, owner.getTable(), sessionFactoryBeanName);

        if (!property.isOwningSide()) {
            collection.setInverse(true);
        }
    }

    if (pc != null && pc.getBatchSize() != null) {
        collection.setBatchSize(pc.getBatchSize().intValue());
    }

    // set up second pass
    if (collection instanceof org.hibernate.mapping.Set) {
        mappings.addSecondPass(
                new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else if (collection instanceof org.hibernate.mapping.List) {
        mappings.addSecondPass(new ListSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else if (collection instanceof org.hibernate.mapping.Map) {
        mappings.addSecondPass(new MapSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else { // Collection -> Bag
        mappings.addSecondPass(
                new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName));
    }
}

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

License:Apache License

/**
 * Creates the DependentValue object that forms a primary key reference for the collection.
 *
 * @param mappings/*from   w w  w  . j a v a  2 s .co m*/
 * @param property          The grails property
 * @param collection        The collection object
 * @param persistentClasses
 * @return The DependantValue (key)
 */
private static DependantValue createPrimaryKeyValue(Mappings mappings,
        @SuppressWarnings("unused") GrailsDomainClassProperty property, Collection collection,
        @SuppressWarnings("unused") Map<?, ?> persistentClasses) {
    KeyValue keyValue;
    DependantValue key;
    String propertyRef = collection.getReferencedPropertyName();
    // this is to support mapping by a property
    if (propertyRef == null) {
        keyValue = collection.getOwner().getIdentifier();
    } else {
        keyValue = (KeyValue) collection.getOwner().getProperty(propertyRef).getValue();
    }

    if (LOG.isDebugEnabled())
        LOG.debug("[GrailsDomainBinder] creating dependant key value  to table ["
                + keyValue.getTable().getName() + "]");

    key = new DependantValue(mappings, collection.getCollectionTable(), keyValue);

    key.setTypeName(null);
    // make nullable and non-updateable
    key.setNullable(true);
    key.setUpdateable(false);
    return key;
}

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

License:Apache License

/**
 * First pass to bind collection to Hibernate metamodel, sets up second pass
 *
 * @param property   The GrailsDomainClassProperty instance
 * @param collection The collection// w w w .ja va 2s.co  m
 * @param owner      The owning persistent class
 * @param mappings   The Hibernate mappings instance
 * @param path
 */
private static void bindCollection(GrailsDomainClassProperty property, Collection collection,
        PersistentClass owner, Mappings mappings, String path, String sessionFactoryBeanName) {

    // set role
    String propertyName = getNameForPropertyAndPath(property, path);
    collection.setRole(StringHelper.qualify(property.getDomainClass().getFullName(), propertyName));

    PropertyConfig pc = getPropertyConfig(property);
    // configure eager fetching
    if (property.getFetchMode() == GrailsDomainClassProperty.FETCH_EAGER) {
        collection.setFetchMode(FetchMode.JOIN);
    } else if (pc != null && pc.getFetch() != null) {
        collection.setFetchMode(pc.getFetch());
    } else {
        collection.setFetchMode(FetchMode.DEFAULT);
    }

    if (pc != null && pc.getCascade() != null) {
        collection.setOrphanDelete(pc.getCascade().equals(CASCADE_ALL_DELETE_ORPHAN));
    }
    // if it's a one-to-many mapping
    if (shouldBindCollectionWithForeignKey(property)) {
        OneToMany oneToMany = new OneToMany(mappings, collection.getOwner());
        collection.setElement(oneToMany);
        bindOneToMany(property, oneToMany, mappings);
    } else {
        bindCollectionTable(property, mappings, collection, owner.getTable(), sessionFactoryBeanName);

        if (!property.isOwningSide()) {
            collection.setInverse(true);
        }
    }

    if (pc != null && pc.getBatchSize() != null) {
        collection.setBatchSize(pc.getBatchSize().intValue());
    }

    // set up second pass
    if (collection instanceof org.hibernate.mapping.Set) {
        mappings.addSecondPass(
                new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else if (collection instanceof org.hibernate.mapping.List) {
        mappings.addSecondPass(new ListSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else if (collection instanceof org.hibernate.mapping.Map) {
        mappings.addSecondPass(new MapSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else { // Collection -> Bag
        mappings.addSecondPass(
                new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName));
    }
}

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

License:Apache License

/**
 * Creates the DependentValue object that forms a primary key reference for the collection.
 *
 * @param mappings/*ww  w.  ja  va2s  . c  om*/
 * @param property          The grails property
 * @param collection        The collection object
 * @param persistentClasses
 * @return The DependantValue (key)
 */
protected DependantValue createPrimaryKeyValue(Mappings mappings, PersistentProperty property,
        Collection collection, Map<?, ?> persistentClasses) {
    KeyValue keyValue;
    DependantValue key;
    String propertyRef = collection.getReferencedPropertyName();
    // this is to support mapping by a property
    if (propertyRef == null) {
        keyValue = collection.getOwner().getIdentifier();
    } else {
        keyValue = (KeyValue) collection.getOwner().getProperty(propertyRef).getValue();
    }

    if (LOG.isDebugEnabled())
        LOG.debug("[GrailsDomainBinder] creating dependant key value  to table ["
                + keyValue.getTable().getName() + "]");

    key = new DependantValue(mappings, collection.getCollectionTable(), keyValue);

    key.setTypeName(null);
    // make nullable and non-updateable
    key.setNullable(true);
    key.setUpdateable(false);
    return key;
}

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

License:Apache License

/**
 * First pass to bind collection to Hibernate metamodel, sets up second pass
 *
 * @param property   The GrailsDomainClassProperty instance
 * @param collection The collection// w  w  w  .j ava 2 s.  co m
 * @param owner      The owning persistent class
 * @param mappings   The Hibernate mappings instance
 * @param path
 */
protected void bindCollection(ToMany property, Collection collection, PersistentClass owner, Mappings mappings,
        String path, String sessionFactoryBeanName) {

    // set role
    String propertyName = getNameForPropertyAndPath(property, path);
    collection.setRole(qualify(property.getOwner().getName(), propertyName));

    PropertyConfig pc = getPropertyConfig(property);
    // configure eager fetching
    final FetchMode fetchMode = pc.getFetchMode();
    if (fetchMode == FetchMode.JOIN) {
        collection.setFetchMode(FetchMode.JOIN);
    } else if (pc.getFetchMode() != null) {
        collection.setFetchMode(pc.getFetchMode());
    } else {
        collection.setFetchMode(FetchMode.DEFAULT);
    }

    if (pc.getCascade() != null) {
        collection.setOrphanDelete(pc.getCascade().equals(CASCADE_ALL_DELETE_ORPHAN));
    }
    // if it's a one-to-many mapping
    if (shouldBindCollectionWithForeignKey(property)) {
        OneToMany oneToMany = new OneToMany(mappings, collection.getOwner());
        collection.setElement(oneToMany);
        bindOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, oneToMany, mappings);
    } else {
        bindCollectionTable(property, mappings, collection, owner.getTable(), sessionFactoryBeanName);

        if (!property.isOwningSide()) {
            collection.setInverse(true);
        }
    }

    if (pc.getBatchSize() != null) {
        collection.setBatchSize(pc.getBatchSize());
    }

    // set up second pass
    if (collection instanceof org.hibernate.mapping.Set) {
        mappings.addSecondPass(
                new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else if (collection instanceof org.hibernate.mapping.List) {
        mappings.addSecondPass(new ListSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else if (collection instanceof org.hibernate.mapping.Map) {
        mappings.addSecondPass(new MapSecondPass(property, mappings, collection, sessionFactoryBeanName));
    } else { // Collection -> Bag
        mappings.addSecondPass(
                new GrailsCollectionSecondPass(property, mappings, collection, sessionFactoryBeanName));
    }
}