Example usage for org.hibernate.metadata CollectionMetadata getElementType

List of usage examples for org.hibernate.metadata CollectionMetadata getElementType

Introduction

In this page you can find the example usage for org.hibernate.metadata CollectionMetadata getElementType.

Prototype

public Type getElementType();

Source Link

Document

The collection element type

Usage

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

License:Open Source License

@SuppressWarnings("unchecked")
protected static void delete(XSessionImplementor sessionProxy, Object object) {
    if (object != null) {
        SessionFactory sessionFactory = sessionProxy.getRawSessionImpl().getSessionFactory();
        PersistenceContext persistenceContext = ((org.hibernate.internal.SessionImpl) sessionProxy
                .getRawSessionImpl()).getPersistenceContext();
        Map<PersistentCollection, CollectionEntry> collectionEntries = persistenceContext
                .getCollectionEntries();
        for (Entry<PersistentCollection, CollectionEntry> entry : collectionEntries.entrySet()) {
            PersistentCollection persistentCollection = entry.getKey();
            if (persistentCollection.wasInitialized()) {
                CollectionMetadata collectionMetadata = sessionFactory
                        .getCollectionMetadata(persistentCollection.getRole());
                Class<?> elementClass = collectionMetadata.getElementType().getReturnedClass();
                if (elementClass.isAssignableFrom(object.getClass())) {
                    if (persistentCollection instanceof Map<?, ?>) {
                        ((Map<?, ?>) persistentCollection).values().remove(object);
                    } else if (persistentCollection instanceof Collection<?>) {
                        ((Collection<?>) persistentCollection).remove(object);
                    }// w w  w  . ja  va2  s.c  om
                }
            }
        }
        Class<?> clazz = object.getClass();
        Collection<HbmReference> hbmReferences = null;
        NavigableMap<Class<?>, Collection<HbmReference>> hbmReferencesByTargetClass = (NavigableMap<Class<?>, Collection<HbmReference>>) ((XSessionFactoryImplementor) sessionProxy
                .getFactory()).getInternalData(SessionFactoryImplWrapper.IDK_HBM_REFERENCES_BY_TARGET_CLASS);
        for (Entry<Class<?>, Collection<HbmReference>> entry : hbmReferencesByTargetClass.descendingMap()
                .entrySet()) {
            if (entry.getKey().isAssignableFrom(clazz)) {
                hbmReferences = entry.getValue();
                break;
            }
        }
        if (hbmReferences != null) {
            EntityReferenceComparator<? super Object> referenceComparator = EntityReferenceComparator
                    .getInstance();
            Entry<Object, EntityEntry>[] entityEntries = persistenceContext.reentrantSafeEntityEntries();
            if (entityEntries != null) {
                for (Entry<Object, EntityEntry> entry : entityEntries) {
                    Object entity = entry.getKey();
                    if (Hibernate.isInitialized(entity)) {
                        EntityPersister persister = entry.getValue().getPersister();
                        ClassMetadata classMetadata = persister.getClassMetadata();
                        for (HbmReference hbmReference : hbmReferences) {
                            if (hbmReference.ownerMetadata == classMetadata) {
                                Object expectedObject = persister.getPropertyValue(entity,
                                        hbmReference.propertyIndex);
                                if (referenceComparator.same(expectedObject, object)) {
                                    persister.setPropertyValue(entity, hbmReference.propertyIndex, null);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    sessionProxy.getRawSessionImpl().delete(object);
}

From source file:org.beanfuse.entity.context.HibernateEntityContext.java

License:Open Source License

private CollectionType buildCollectionType(SessionFactory sessionFactory, Class collectionClass, String role) {
    CollectionMetadata cm = sessionFactory.getCollectionMetadata(role);
    org.hibernate.type.Type type = cm.getElementType();
    EntityType elementType = null;//from  ww  w  . ja  v  a2 s .  c  o  m
    if (type.isEntityType()) {
        elementType = (EntityType) entityTypes.get(type.getName());
        if (null == elementType) {
            elementType = buildEntityType(sessionFactory, type.getName());
        }
    } else {
        elementType = new EntityType(type.getReturnedClass());
    }

    CollectionType collectionType = new CollectionType();
    collectionType.setElementType(elementType);
    collectionType.setArray(cm.isArray());
    collectionType.setCollectionClass(collectionClass);
    if (!collectionTypes.containsKey(collectionType.getName())) {
        collectionTypes.put(collectionType.getName(), collectionType);
    }
    return collectionType;
}

From source file:org.beangle.commons.orm.hibernate.internal.HibernateEntityContext.java

License:Open Source License

private CollectionType buildCollectionType(SessionFactory sessionFactory, Class<?> collectionClass,
        String role) {//from w ww.  j  a v  a2  s.co  m
    CollectionMetadata cm = sessionFactory.getCollectionMetadata(role);
    // FIXME buildCollectionType
    if (null == cm)
        return null;
    org.hibernate.type.Type type = cm.getElementType();
    EntityType elementType = null;
    if (type.isEntityType()) {
        elementType = (EntityType) entityTypes.get(type.getName());
        if (null == elementType)
            elementType = buildEntityType(sessionFactory, type.getName());
    } else {
        elementType = new EntityType(type.getReturnedClass());
    }

    CollectionType collectionType = new CollectionType();
    collectionType.setElementType(elementType);
    collectionType.setArray(cm.isArray());
    collectionType.setCollectionClass(collectionClass);
    if (!collectionTypes.containsKey(collectionType.getName())) {
        collectionTypes.put(collectionType.getName(), collectionType);
    }
    return collectionType;
}

From source file:org.beangle.model.persist.hibernate.HibernateEntityContext.java

License:Open Source License

private CollectionType buildCollectionType(SessionFactory sessionFactory, Class<?> collectionClass,
        String role) {//  w ww .j  a va2 s.co m
    CollectionMetadata cm = sessionFactory.getCollectionMetadata(role);
    // FIXME buildCollectionType
    if (null == cm) {
        return null;
    }
    org.hibernate.type.Type type = cm.getElementType();
    EntityType elementType = null;
    if (type.isEntityType()) {
        elementType = (EntityType) entityTypes.get(type.getName());
        if (null == elementType) {
            elementType = buildEntityType(sessionFactory, type.getName());
        }
    } else {
        elementType = new EntityType(type.getReturnedClass());
    }

    CollectionType collectionType = new CollectionType();
    collectionType.setElementType(elementType);
    collectionType.setArray(cm.isArray());
    collectionType.setCollectionClass(collectionClass);
    if (!collectionTypes.containsKey(collectionType.getName())) {
        collectionTypes.put(collectionType.getName(), collectionType);
    }
    return collectionType;
}

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

License:Open Source License

private CollectionType buildCollectionType(SessionFactory sessionFactory, Class<?> collectionClass,
        String role) {//from  www  .ja v a2s.co m
    CollectionMetadata cm = sessionFactory.getCollectionMetadata(role);
    // FIXME buildCollectionType in class hierarchy
    if (null == cm)
        return null;
    org.hibernate.type.Type type = cm.getElementType();
    EntityType elementType = null;
    if (type.isEntityType()) {
        elementType = (EntityType) entityTypes.get(type.getName());
        if (null == elementType)
            elementType = buildEntityType(sessionFactory, type.getName());
    } else {
        elementType = new EntityType(type.getReturnedClass());
    }

    CollectionType collectionType = new CollectionType();
    collectionType.setElementType(elementType);
    collectionType.setArray(cm.isArray());
    collectionType.setCollectionClass(collectionClass);
    if (!collectionTypes.containsKey(collectionType.getName())) {
        collectionTypes.put(collectionType.getName(), collectionType);
    }
    return collectionType;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

License:Open Source License

/**
 * Processes changes to persistent collection that contains instances of OpenmrsObject objects.
 * <p>/*  w  ww  .jav a 2s.  com*/
 * Remarks:
 * <p>
 * Xml 'schema' for the sync item content for the persisted collection follows. Note that for persisted
 * collections syncItemKey is a composite of owner object uuid and the property name that contains the
 * collection. <br/>
 * &lt;persistent-collection&gt; element: wrapper element <br/>
 * &lt;owner uuid='' propertyName='' type='' action='recreate|update' &gt; element: this
 * captures the information about the object that holds reference to the collection being
 * processed <br/>
 * -uuid: owner object uuid <br/>
 * -properyName: names of the property on owner object that holds this collection <br/>
 * -type: owner class name <br/>
 * -action: recreate, update -- these are collection events defined by hibernate interceptor <br/>
 * &lt;entry action='update|delete' uuid='' type='' &gt; element: this captures info about
 * individual collection entries: <br/>
 * -action: what is being done to this item of the collection: delete (item was removed from the
 * collection) or update (item was added to the collection) <br/>
 * -uuid: entry's uuid <br/>
 * -type: class name
 *
 * @param collection Instance of Hibernate AbstractPersistentCollection to process.
 * @param key key of owner for the collection.
 * @param action action being performed on the collection: update, recreate
 */
private void processPersistentCollection(AbstractPersistentCollection collection, Serializable key,
        String action, String originalRecordUuid, OpenmrsObject owner, String ownerPropertyName) {

    LinkedHashMap<String, OpenmrsObject> entriesHolder = null;

    // Setup the serialization data structures to hold the state
    Package pkg = new Package();
    entriesHolder = new LinkedHashMap<String, OpenmrsObject>();
    try {

        CollectionMetadata collMD = getCollectionMetadata(owner.getClass(), ownerPropertyName,
                getSessionFactory());
        if (collMD == null) {
            throw new SyncException(
                    "Can't find a collection with " + ownerPropertyName + " in class " + owner.getClass());
        }

        Class<?> elementClass = collMD.getElementType().getReturnedClass();
        //If this is a simple type like Integer, serialization of the collection will be as below:
        //<org.openmrs.Cohort>
        //   <memberIds type="java.util.Set(org.openmrs.Cohort)">[2, 3]</memberIds>
        //  ............. and more
        //This should work just fine as long as there is a Normalizer registered for it
        if (!OpenmrsObject.class.isAssignableFrom(elementClass)
                && SyncUtil.getNormalizer(elementClass) != null) {

            //Check if there is already a NEW/UPDATE sync item for the owner
            SyncItem syncItem = new SyncItem();
            syncItem.setKey(new SyncItemKey<String>(owner.getUuid(), String.class));
            syncItem.setContainedType(owner.getClass());
            syncItem.setState(SyncItemState.UPDATED);

            boolean ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);
            syncItem.setState(SyncItemState.NEW);
            if (!ownerHasSyncItem)
                ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);

            if (!ownerHasSyncItem) {
                ClassMetadata cmd = getSessionFactory().getClassMetadata(owner.getClass());
                //create an UPDATE sync item for the owner so that the collection changes get recorded along
                Serializable primaryKeyValue = cmd.getIdentifier(owner,
                        (SessionImplementor) getSessionFactory().getCurrentSession());
                packageObject(owner, cmd.getPropertyValues(owner, EntityMode.POJO), cmd.getPropertyNames(),
                        cmd.getPropertyTypes(), primaryKeyValue, SyncItemState.UPDATED);
            } else {
                //There is already an UPDATE OR NEW SyncItem for the owner containing the above updates
            }

            return;
        }
        // find out what entries need to be serialized
        for (Object entry : (Iterable) collection) {
            if (entry instanceof OpenmrsObject) {
                OpenmrsObject obj = (OpenmrsObject) entry;

                // attempt to retrieve entry uuid
                String entryUuid = obj.getUuid();
                if (entryUuid == null) {
                    entryUuid = fetchUuid(obj);
                    if (log.isDebugEnabled()) {
                        log.debug("Entry uuid was null, attempted to fetch uuid with the following results");
                        log.debug("Entry type:" + obj.getClass().getName() + ",uuid:" + entryUuid);
                    }
                }
                // well, this is messed up: have an instance of
                // OpenmrsObject but has no uuid
                if (entryUuid == null) {
                    log.error("Cannot handle collection entries where uuid is null.");
                    throw new CallbackException("Cannot handle collection entries where uuid is null.");
                }

                // add it to the holder to avoid possible duplicates: key =
                // uuid + action
                entriesHolder.put(entryUuid + "|update", obj);
            } else {
                log.warn(
                        "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers. Type was "
                                + entry.getClass() + " in property " + ownerPropertyName + " in class "
                                + owner.getClass());
                // skip out early because we don't want to write any xml for it
                // it was handled by the normal property writer hopefully
                return;
            }
        }

        // add on deletes
        if (!"recreate".equals(action) && collection.getRole() != null) {
            org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory())
                    .getCollectionPersister(collection.getRole());
            Iterator it = collection.getDeletes(persister, false);
            if (it != null) {
                while (it.hasNext()) {
                    Object entryDelete = it.next();
                    if (entryDelete instanceof OpenmrsObject) {
                        OpenmrsObject objDelete = (OpenmrsObject) entryDelete;
                        // attempt to retrieve entry uuid
                        String entryDeleteUuid = objDelete.getUuid();
                        if (entryDeleteUuid == null) {
                            entryDeleteUuid = fetchUuid(objDelete);
                            if (log.isDebugEnabled()) {
                                log.debug(
                                        "Entry uuid was null, attempted to fetch uuid with the following results");
                                log.debug("Entry type:" + entryDeleteUuid.getClass().getName() + ",uuid:"
                                        + entryDeleteUuid);
                            }
                        }
                        // well, this is messed up: have an instance of
                        // OpenmrsObject but has no uuid
                        if (entryDeleteUuid == null) {
                            log.error("Cannot handle collection delete entries where uuid is null.");
                            throw new CallbackException(
                                    "Cannot handle collection delete entries where uuid is null.");
                        }

                        // add it to the holder to avoid possible
                        // duplicates: key = uuid + action
                        // also, only add if there is no update action for the same object: see SYNC-280
                        if (!entriesHolder.containsKey(entryDeleteUuid + "|update")) {
                            entriesHolder.put(entryDeleteUuid + "|delete", objDelete);
                        }

                    } else {
                        // TODO: more debug info
                        log.warn(
                                "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers!");
                        // skip out early because we don't want to write any
                        // xml for it. it
                        // was handled by the normal property writer
                        // hopefully
                        return;
                    }
                }
            }
        }

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal. note: when making SyncItemKey, make it a composite
         * string of uuid + prop. name to avoid collisions with updates to
         * parent object or updates to more than one collection on same
         * owner
         */

        // Setup the serialization data structures to hold the state
        Record xml = pkg.createRecordForWrite(collection.getClass().getName());
        Item entityItem = xml.getRootItem();

        // serialize owner info: we will need type, prop name where collection
        // goes, and owner uuid
        Item item = xml.createItem(entityItem, "owner");
        item.setAttribute("type", this.getType(owner));
        item.setAttribute("properyName", ownerPropertyName);
        item.setAttribute("action", action);
        item.setAttribute("uuid", owner.getUuid());

        // build out the xml for the item content
        Boolean hasNoAutomaticPrimaryKey = null;
        String type = null;
        for (String entryKey : entriesHolder.keySet()) {
            OpenmrsObject entryObject = entriesHolder.get(entryKey);
            if (type == null) {
                type = this.getType(entryObject);
                hasNoAutomaticPrimaryKey = SyncUtil.hasNoAutomaticPrimaryKey(type);
            }

            Item temp = xml.createItem(entityItem, "entry");
            temp.setAttribute("type", type);
            temp.setAttribute("action", entryKey.substring(entryKey.indexOf('|') + 1));
            temp.setAttribute("uuid", entryObject.getUuid());
            if (hasNoAutomaticPrimaryKey) {
                temp.setAttribute("primaryKey", getSyncService().getPrimaryKey(entryObject));
            }
        }

        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(owner.getUuid() + "|" + ownerPropertyName, String.class));
        syncItem.setState(SyncItemState.UPDATED);
        syncItem.setContainedType(collection.getClass());
        syncItem.setContent(xml.toStringAsDocumentFragement());

        getSyncRecord().addOrRemoveAndAddItem(syncItem);
        getSyncRecord().addContainedClass(owner.getClass().getName());

        // do the original uuid dance, same as in packageObject
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (Exception ex) {
        log.error("Error processing Persistent collection, see callstack and inner expection", ex);
        throw new CallbackException(
                "Error processing Persistent collection, see callstack and inner expection.", ex);
    }
}

From source file:org.springframework.flex.core.io.HibernateConfigProcessor.java

License:Apache License

/**
 * /*from  www. j  a  v a2s.  c  o m*/
 * {@inheritDoc}
 */
@Override
protected Set<Class<?>> findTypesToRegister() {
    Set<Class<?>> typesToRegister = new HashSet<Class<?>>();
    if (hibernateConfigured) {
        for (ClassMetadata classMetadata : this.classMetadata) {
            if (!classMetadata.getMappedClass(EntityMode.POJO).isInterface()) {
                typesToRegister.add(classMetadata.getMappedClass(EntityMode.POJO));
                findComponentProperties(classMetadata.getPropertyTypes(), typesToRegister);
            }
        }
        for (CollectionMetadata collectionMetadata : this.collectionMetadata) {
            Type elementType = collectionMetadata.getElementType();
            if (elementType instanceof ComponentType) {
                if (!elementType.getReturnedClass().isInterface()) {
                    typesToRegister.add(elementType.getReturnedClass());
                    findComponentProperties(((ComponentType) elementType).getSubtypes(), typesToRegister);
                }
            }
        }
    }
    return typesToRegister;
}

From source file:org.springframework.flex.core.io.LocalJpaHibernateConfigProcessor.java

License:Apache License

/**
 *
 * {@inheritDoc}/*w ww.  j  ava  2s.  co  m*/
 */
@Override
protected Set<Class<?>> findTypesToRegister() {
    Set<Class<?>> typesToRegister = new HashSet<Class<?>>();
    if (hibernateConfigured) {
        for (ClassMetadata classMetadata : this.classMetadata) {
            if (!classMetadata.getMappedClass().isInterface()) {
                typesToRegister.add(classMetadata.getMappedClass());
                findComponentProperties(classMetadata.getPropertyTypes(), typesToRegister);
            }
        }
        for (CollectionMetadata collectionMetadata : this.collectionMetadata) {
            Type elementType = collectionMetadata.getElementType();
            if (elementType instanceof ComponentType) {
                if (!elementType.getReturnedClass().isInterface()) {
                    typesToRegister.add(elementType.getReturnedClass());
                    findComponentProperties(((ComponentType) elementType).getSubtypes(), typesToRegister);
                }
            }
        }
    }
    return typesToRegister;
}