List of usage examples for org.hibernate.type CollectionType getRole
public String getRole()
From source file:ar.com.zauber.commons.repository.query.visitor.CriteriaFilterVisitor.java
License:Apache License
/** * Obtiene la clase del siguiente pathPart a procesar. * * @param pathPartClass Clase de un partPath recien procesado * @param pathPart siguiente pathPart a procesar * @return//from w ww .j a v a 2 s .com */ private Class<?> getNextPathPartClass(final Class<?> pathPartClass, final String pathPart) { Type hibernateType = null; Class<?> nextPathPartClass = null; // se obtiene el tipo de hibernate del pathPart actual ClassMetadata classMetadata = sessionFactory.getClassMetadata(pathPartClass); if (classMetadata != null) { // pathPartClass no es un componente hibernateType = classMetadata.getPropertyType(pathPart); } else { hibernateType = getHibernateTypeFromComponent(pathPart); } // si es una coleccion se obtiene el tipo del elemento de la coleccion if (hibernateType instanceof CollectionType) { CollectionType collectionType = (CollectionType) hibernateType; hibernateType = sessionFactory.getCollectionMetadata(collectionType.getRole()).getElementType(); } // se resuelve la clase del atributo de busqueda // sobre el que se esta actualmente if (hibernateType instanceof EntityType) { nextPathPartClass = ((EntityType) hibernateType).getReturnedClass(); } else if (hibernateType instanceof ComponentType) { componentType = (ComponentType) hibernateType; nextPathPartClass = componentType.getReturnedClass(); } return nextPathPartClass; }
From source file:com.miranteinfo.seam.hibernate.HibernateCascade.java
License:Open Source License
/** * Cascade an action to a collection/* w w w . j a v a 2s .c om*/ */ private void cascadeCollection(final Object child, final CascadeStyle style, final Object anything, final CollectionType type) { CollectionPersister persister = eventSource.getFactory().getCollectionPersister(type.getRole()); Type elemType = persister.getElementType(); final int oldCascadeTo = cascadeTo; if (cascadeTo == AFTER_INSERT_BEFORE_DELETE) { cascadeTo = AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION; } //cascade to current collection elements if (elemType.isEntityType() || elemType.isAnyType() || elemType.isComponentType()) { cascadeCollectionElements(child, type, style, elemType, anything, persister.isCascadeDeleteEnabled()); } cascadeTo = oldCascadeTo; }
From source file:com.miranteinfo.seam.hibernate.HibernateCascade.java
License:Open Source License
/** * Cascade to the collection elements// w w w . j a va 2 s.c o m */ private void cascadeCollectionElements(final Object child, final CollectionType collectionType, final CascadeStyle style, final Type elemType, final Object anything, final boolean isCascadeDeleteEnabled) throws HibernateException { // we can't cascade to non-embedded elements boolean embeddedElements = eventSource.getEntityMode() != EntityMode.DOM4J || ((EntityType) collectionType.getElementType(eventSource.getFactory())).isEmbeddedInXML(); boolean reallyDoCascade = style.reallyDoCascade(action) && embeddedElements && child != CollectionType.UNFETCHED_COLLECTION; if (reallyDoCascade) { if (log.isTraceEnabled()) { log.trace("cascade " + action + " for collection: " + collectionType.getRole()); } Iterator iter = action.getCascadableChildrenIterator(eventSource, collectionType, child); while (iter.hasNext()) { cascadeProperty(iter.next(), elemType, style, anything, isCascadeDeleteEnabled); } if (log.isTraceEnabled()) { log.trace("done cascade " + action + " for collection: " + collectionType.getRole()); } } final boolean deleteOrphans = hasOrphanDelete(style) && action.deleteOrphans() && elemType.isEntityType() && child instanceof PersistentCollection; //a newly instantiated collection can't have orphans if (deleteOrphans) { // handle orphaned entities!! if (log.isTraceEnabled()) { log.trace("deleting orphans for collection: " + collectionType.getRole()); } // we can do the cast since orphan-delete does not apply to: // 1. newly instantiated collections // 2. arrays (we can't track orphans for detached arrays) final String entityName = collectionType.getAssociatedEntityName(eventSource.getFactory()); deleteOrphans(entityName, (PersistentCollection) child); if (log.isTraceEnabled()) { log.trace("done deleting orphans for collection: " + collectionType.getRole()); } } }
From source file:cz.jirutka.rsql.visitor.hibernate.HibernateCriterionVisitor.java
License:Apache License
private Tuple<Type, String>[] getPath(ClassMetadata classMetadata, String[] names) { Tuple<Type, String>[] path = new Tuple[names.length]; Object element = classMetadata; for (int i = 0; i < names.length; ++i) { String name = names[i];/*from w ww .j a v a 2s .c o m*/ Type propertyType = getPropertyType(element, name); path[i] = new Tuple<Type, String>(propertyType, name); if (propertyType.isCollectionType()) { CollectionType collectionType = (CollectionType) propertyType; String associatedEntityName = collectionType.getRole(); CollectionPersister collectionPersister = getSessionFactory() .getCollectionPersister(associatedEntityName); element = collectionPersister.getElementType(); } else if (propertyType.isAssociationType()) { AssociationType associationType = (AssociationType) propertyType; String associatedEntityName = associationType.getAssociatedEntityName(getSessionFactory()); element = getSessionFactory().getClassMetadata(associatedEntityName); } else if (propertyType.isComponentType()) { element = propertyType; } } return path; }
From source file:ome.services.graphs.GraphPathBean.java
License:Open Source License
/** * Process the Hibernate domain object model to initialize this class' instance fields. * No other method should write to them. * @param sessionFactory the Hibernate session factory *//*from w w w.ja v a 2 s .c o m*/ private void initialize(SessionFactoryImplementor sessionFactory) { /* note all the direct superclasses */ final Map<String, String> superclasses = new HashMap<String, String>(); final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata(); for (final String className : classesMetadata.keySet()) { try { final Class<?> actualClass = Class.forName(className); if (IObject.class.isAssignableFrom(actualClass)) { classesBySimpleName.put(actualClass.getSimpleName(), actualClass.asSubclass(IObject.class)); final Set<String> subclassNames = sessionFactory.getEntityPersister(className) .getEntityMetamodel().getSubclassEntityNames(); for (final String subclassName : subclassNames) { if (!subclassName.equals(className)) { final Class<?> actualSubclass = Class.forName(subclassName); if (actualSubclass.getSuperclass() == actualClass) { superclasses.put(subclassName, className); } } } } else { log.warn("mapped class " + className + " is not a " + IObject.class.getName()); } } catch (ClassNotFoundException e) { log.error("could not instantiate class", e); } } /* note the indirect superclasses and subclasses */ for (final Entry<String, String> superclassRelationship : superclasses.entrySet()) { final String startClass = superclassRelationship.getKey(); String superclass = superclassRelationship.getValue(); while (superclass != null) { allSuperclasses.put(startClass, superclass); allSubclasses.put(superclass, startClass); superclass = superclasses.get(superclass); } } /* queue for processing all the properties of all the mapped entities: name, type, nullability */ final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>(); final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>(); for (final Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) { final String className = classMetadata.getKey(); final ClassMetadata metadata = classMetadata.getValue(); /* note name of identifier property */ classIdProperties.put(metadata.getEntityName(), metadata.getIdentifierPropertyName()); /* queue other properties */ final String[] propertyNames = metadata.getPropertyNames(); final Type[] propertyTypes = metadata.getPropertyTypes(); final boolean[] propertyNullabilities = metadata.getPropertyNullability(); for (int i = 0; i < propertyNames.length; i++) { final List<String> propertyPath = Collections.singletonList(propertyNames[i]); propertyQueue.add( new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i])); } final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length); propertyNamesSet.addAll(Arrays.asList(propertyNames)); allPropertyNames.put(className, propertyNamesSet); } /* process each property to note entity linkages */ while (!propertyQueue.isEmpty()) { final PropertyDetails property = propertyQueue.remove(); if (ignoreProperty(property.path.get(property.path.size() - 1))) { continue; } /* if the property has a component type, queue the parts for processing */ if (property.type instanceof ComponentType) { final ComponentType componentType = (ComponentType) property.type; final String[] componentPropertyNames = componentType.getPropertyNames(); final Type[] componentPropertyTypes = componentType.getSubtypes(); final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability(); for (int i = 0; i < componentPropertyNames.length; i++) { final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1); componentPropertyPath.addAll(property.path); componentPropertyPath.add(componentPropertyNames[i]); propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath, componentPropertyTypes[i], componentPropertyNullabilities[i])); } } else { /* determine if another mapped entity class is linked by this property */ final boolean isAssociatedEntity; if (property.type instanceof CollectionType) { final CollectionType ct = (CollectionType) property.type; isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType() .isEntityType(); } else { isAssociatedEntity = property.type instanceof AssociationType; } /* the property can link to entities, so process it further */ String propertyPath = Joiner.on('.').join(property.path); /* find if the property is accessible (e.g., not protected) */ boolean propertyIsAccessible = false; String classToInstantiateName = property.holder; Class<?> classToInstantiate = null; try { classToInstantiate = Class.forName(classToInstantiateName); while (Modifier.isAbstract(classToInstantiate.getModifiers())) { classToInstantiateName = allSubclasses.get(classToInstantiateName).iterator().next(); classToInstantiate = Class.forName(classToInstantiateName); } try { PropertyUtils.getNestedProperty(classToInstantiate.newInstance(), propertyPath); propertyIsAccessible = true; } catch (NoSuchMethodException e) { /* expected for collection properties */ } catch (NestedNullException e) { log.debug("guessing " + propertyPath + " of " + property.holder + " to be accessible"); propertyIsAccessible = true; } } catch (ReflectiveOperationException e) { log.error("could not probe property " + propertyPath + " of " + property.holder, e); continue; } /* build property report line for log */ final char arrowShaft = property.isNullable ? '-' : '='; final StringBuffer sb = new StringBuffer(); sb.append(property.holder); sb.append(' '); for (final String propertyName : property.path) { sb.append(arrowShaft); sb.append(arrowShaft); sb.append(propertyName); } sb.append(arrowShaft); sb.append(arrowShaft); sb.append("> "); final String valueClassName; if (isAssociatedEntity) { valueClassName = ((AssociationType) property.type).getAssociatedEntityName(sessionFactory); sb.append(valueClassName); } else { valueClassName = null; sb.append("value"); } if (property.type.isCollectionType()) { sb.append("[]"); } if (!propertyIsAccessible) { sb.append(" (inaccessible)"); } /* determine from which class the property is inherited, if at all */ String superclassWithProperty = null; String currentClass = property.holder; while (true) { currentClass = superclasses.get(currentClass); if (currentClass == null) { break; } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) { superclassWithProperty = currentClass; } } /* check if the property actually comes from an interface */ final String declaringClassName = superclassWithProperty == null ? property.holder : superclassWithProperty; final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName, property.path.get(0)); /* report where the property is declared */ if (superclassWithProperty != null) { sb.append(" from "); sb.append(superclassWithProperty); } else { if (interfaceForProperty != null) { sb.append(" see "); sb.append(interfaceForProperty.getName()); /* It would be nice to set PropertyDetails to have the interface as the holder, * but then properties would not be unique by declarer class and instance ID. */ } /* entity linkages by non-inherited properties are recorded */ if (valueClassName == null && property.path.size() > 1) { /* assume that the top-level property suffices for describing simple properties */ log.debug("recording " + propertyPath + " as " + property.path.get(0)); propertyPath = property.path.get(0); } final Entry<String, String> classPropertyName = Maps.immutableEntry(property.holder, propertyPath); if (valueClassName == null) { simpleProperties.put(property.holder, propertyPath); } else { linkedTo.put(property.holder, Maps.immutableEntry(valueClassName, propertyPath)); linkedBy.put(valueClassName, classPropertyName); } final PropertyKind propertyKind; if (property.type.isCollectionType()) { propertyKind = PropertyKind.COLLECTION; } else if (property.isNullable) { propertyKind = PropertyKind.OPTIONAL; } else { propertyKind = PropertyKind.REQUIRED; } propertyKinds.put(classPropertyName, propertyKind); if (propertyIsAccessible) { accessibleProperties.add(classPropertyName); } } if (log.isDebugEnabled()) { log.debug(sb.toString()); } } } log.info("initialized graph path bean with " + propertyKinds.size() + " properties"); }
From source file:ome.services.graphs.GraphPathReport.java
License:Open Source License
/** * Process the Hibernate domain object model and write a report of the mapped objects. * @throws IOException if there was a problem in writing to the output file *///w ww . j a v a2s. c om private static void report() throws IOException { /* note all the direct superclasses and subclasses */ final Map<String, String> superclasses = new HashMap<String, String>(); final SortedSetMultimap<String, String> subclasses = TreeMultimap.create(); @SuppressWarnings("unchecked") final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata(); for (final String className : classesMetadata.keySet()) { try { final Class<?> actualClass = Class.forName(className); if (IObject.class.isAssignableFrom(actualClass)) { @SuppressWarnings("unchecked") final Set<String> subclassNames = sessionFactory.getEntityPersister(className) .getEntityMetamodel().getSubclassEntityNames(); for (final String subclassName : subclassNames) { if (!subclassName.equals(className)) { final Class<?> actualSubclass = Class.forName(subclassName); if (actualSubclass.getSuperclass() == actualClass) { superclasses.put(subclassName, className); subclasses.put(getSimpleName(className), getSimpleName(subclassName)); } } } } else { System.err.println("error: mapped class " + className + " is not a " + IObject.class.getName()); } } catch (ClassNotFoundException e) { System.err.println("error: could not instantiate class: " + e); } } /* queue for processing all the properties of all the mapped entities: name, type, nullability */ final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>(); final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>(); for (final Map.Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) { final String className = classMetadata.getKey(); final ClassMetadata metadata = classMetadata.getValue(); final String[] propertyNames = metadata.getPropertyNames(); final Type[] propertyTypes = metadata.getPropertyTypes(); final boolean[] propertyNullabilities = metadata.getPropertyNullability(); for (int i = 0; i < propertyNames.length; i++) { if (!ignoreProperty(propertyNames[i])) { final List<String> propertyPath = Collections.singletonList(propertyNames[i]); propertyQueue.add(new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i])); } } final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length); propertyNamesSet.addAll(Arrays.asList(propertyNames)); allPropertyNames.put(className, propertyNamesSet); } /* for linkedBy, X -> Y, Z: class X is linked to by class Y with Y's property Z */ final SetMultimap<String, Map.Entry<String, String>> linkedBy = HashMultimap.create(); final SetMultimap<String, String> linkers = HashMultimap.create(); final SortedMap<String, SortedMap<String, String>> classPropertyReports = new TreeMap<String, SortedMap<String, String>>(); /* process each property to note entity linkages */ while (!propertyQueue.isEmpty()) { final PropertyDetails property = propertyQueue.remove(); /* if the property has a component type, queue the parts for processing */ if (property.type instanceof ComponentType) { final ComponentType componentType = (ComponentType) property.type; final String[] componentPropertyNames = componentType.getPropertyNames(); final Type[] componentPropertyTypes = componentType.getSubtypes(); final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability(); for (int i = 0; i < componentPropertyNames.length; i++) { if (!ignoreProperty(componentPropertyNames[i])) { final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1); componentPropertyPath.addAll(property.path); componentPropertyPath.add(componentPropertyNames[i]); propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath, componentPropertyTypes[i], componentPropertyNullabilities[i])); } } } else { /* determine if this property links to another entity */ final boolean isAssociatedEntity; if (property.type instanceof CollectionType) { final CollectionType ct = (CollectionType) property.type; isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType() .isEntityType(); } else { isAssociatedEntity = property.type instanceof AssociationType; } /* determine the class and property name for reporting */ final String holderSimpleName = getSimpleName(property.holder); final String propertyPath = Joiner.on('.').join(property.path); /* build a report line for this property */ final StringBuffer sb = new StringBuffer(); final String valueClassName; if (isAssociatedEntity) { /* entity linkages by non-inherited properties are recorded */ final String valueName = ((AssociationType) property.type) .getAssociatedEntityName(sessionFactory); final String valueSimpleName = getSimpleName(valueName); final Map.Entry<String, String> classPropertyName = Maps.immutableEntry(holderSimpleName, propertyPath); linkers.put(holderSimpleName, propertyPath); linkedBy.put(valueSimpleName, classPropertyName); valueClassName = linkTo(valueSimpleName); } else { /* find a Sphinx representation for this property value type */ final UserType userType; if (property.type instanceof CustomType) { userType = ((CustomType) property.type).getUserType(); } else { userType = null; } if (property.type instanceof EnumType) { valueClassName = "enumeration"; } else if (userType instanceof GenericEnumType) { @SuppressWarnings("unchecked") final Class<? extends Unit> unitQuantityClass = ((GenericEnumType) userType) .getQuantityClass(); valueClassName = "enumeration of " + linkToJavadoc(unitQuantityClass.getName()); } else if (property.type instanceof ListType || userType instanceof ListAsSQLArrayUserType) { valueClassName = "list"; } else if (property.type instanceof MapType) { valueClassName = "map"; } else { valueClassName = "``" + property.type.getName() + "``"; } } sb.append(valueClassName); if (property.type.isCollectionType()) { sb.append(" (multiple)"); } else if (property.isNullable) { sb.append(" (optional)"); } /* determine from which class the property is inherited, if at all */ String superclassWithProperty = null; String currentClass = property.holder; while (true) { currentClass = superclasses.get(currentClass); if (currentClass == null) { break; } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) { superclassWithProperty = currentClass; } } /* check if the property actually comes from an interface */ final String declaringClassName = superclassWithProperty == null ? property.holder : superclassWithProperty; final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName, property.path.get(0)); /* report where the property is declared */ if (superclassWithProperty != null) { sb.append(" from "); sb.append(linkTo(getSimpleName(superclassWithProperty))); } else { if (interfaceForProperty != null) { sb.append(", see "); sb.append(linkToJavadoc(interfaceForProperty.getName())); } } SortedMap<String, String> byProperty = classPropertyReports.get(holderSimpleName); if (byProperty == null) { byProperty = new TreeMap<String, String>(); classPropertyReports.put(holderSimpleName, byProperty); } byProperty.put(propertyPath, sb.toString()); } } /* the information is gathered, now write the report */ out.write("Glossary of all OMERO Model Objects\n"); out.write("===================================\n\n"); out.write("Overview\n"); out.write("--------\n\n"); out.write("Reference\n"); out.write("---------\n\n"); for (final Map.Entry<String, SortedMap<String, String>> byClass : classPropertyReports.entrySet()) { /* label the class heading */ final String className = byClass.getKey(); out.write(".. _" + labelFor(className) + ":\n\n"); out.write(className + "\n"); final char[] underline = new char[className.length()]; for (int i = 0; i < underline.length; i++) { underline[i] = '"'; } out.write(underline); out.write("\n\n"); /* note the class' relationships */ final SortedSet<String> superclassOf = new TreeSet<String>(); for (final String subclass : subclasses.get(className)) { superclassOf.add(linkTo(subclass)); } final SortedSet<String> linkerText = new TreeSet<String>(); for (final Map.Entry<String, String> linker : linkedBy.get(className)) { linkerText.add(linkTo(linker.getKey(), linker.getValue())); } if (!(superclassOf.isEmpty() && linkerText.isEmpty())) { /* write the class' relationships */ /* out.write("Relationships\n"); out.write("^^^^^^^^^^^^^\n\n"); */ if (!superclassOf.isEmpty()) { out.write("Subclasses: " + Joiner.on(", ").join(superclassOf) + "\n\n"); } if (!linkerText.isEmpty()) { out.write("Used by: " + Joiner.on(", ").join(linkerText) + "\n\n"); } } /* write the class' properties */ /* out.write("Properties\n"); out.write("^^^^^^^^^^\n\n"); */ out.write("Properties:\n"); for (final Map.Entry<String, String> byProperty : byClass.getValue().entrySet()) { final String propertyName = byProperty.getKey(); // if (linkers.containsEntry(className, propertyName)) { // /* label properties that have other entities as values */ // out.write(".. _" + labelFor(className, propertyName) + ":\n\n"); // } out.write(" | " + propertyName + ": " + byProperty.getValue() + "\n" /* \n */); } out.write("\n"); } }
From source file:org.compass.gps.device.hibernate.lifecycle.HibernateEventListenerUtils.java
License:Apache License
public static Collection getUnpersistedCascades(CompassGpsInterfaceDevice compassGps, Object entity, SessionFactoryImplementor sessionFactory, Cascade cascade, Collection visited) { if (visited.contains(entity)) { return Collections.EMPTY_SET; }//from ww w.j a v a 2s . co m visited.add(entity); ClassMetadata classMetadata = sessionFactory.getClassMetadata(entity.getClass()); if (classMetadata == null) { for (Iterator iter = sessionFactory.getAllClassMetadata().values().iterator(); iter.hasNext();) { ClassMetadata temp = (ClassMetadata) iter.next(); if (entity.getClass().equals(temp.getMappedClass(EntityMode.POJO))) { classMetadata = temp; break; } } } Assert.notNull(classMetadata, "Failed to lookup Hibernate ClassMetadata for entity [" + entity + "]"); String entityName = classMetadata.getEntityName(); EntityPersister persister = sessionFactory.getEntityPersister(entityName); CompassMapping compassMapping = ((InternalCompass) compassGps.getIndexCompass()).getMapping(); ClassMapping classMapping = (ClassMapping) compassMapping.getMappingByClass(entity.getClass()); if (classMapping == null) { return Collections.EMPTY_SET; } // CascadeStyle[] cascadeStyles = persister.getEntityMetamodel().getCascadeStyles(); String[] propertyNames = persister.getPropertyNames(); Type[] types = persister.getPropertyTypes(); Set dependencies = new HashSet(); for (int i = 0, len = propertyNames.length; i < len; i++) { // property cascade includes save/update? // CascadeStyle cascadeStyle = cascadeStyles[i]; // if (!cascadeStyle.doCascade(CascadingAction.SAVE_UPDATE)) { // continue; // } // property is mapped in Compass? String name = propertyNames[i]; Mapping mapping = classMapping.getMapping(name); if (mapping == null) { continue; } // property value is not null? Object propertyValue = persister.getPropertyValue(entity, name, EntityMode.POJO); if (propertyValue == null) { continue; } // find actual property type // todo may not be correct see http://www.hibernate.org/hib_docs/v3/api/org/hibernate/type/EntityType.html#getReturnedClass() // todo may need to use class name string comparison instead Class propertyType; Type type = types[i]; boolean collection = false; if (type instanceof CollectionType) { CollectionType collectionType = (CollectionType) type; propertyType = persister.getFactory().getCollectionPersister(collectionType.getRole()) .getElementType().getReturnedClass(); collection = true; } else { propertyType = type.getReturnedClass(); } // Mirroring is cascaded for this property? if (!compassGps.hasMappingForEntityForMirror(propertyType, cascade)) { continue; } // find dependent unpersisted property value(s) ResourceMapping propertyTypeMapping = compassMapping.getMappingByClass(propertyType); Mapping[] idMappings = propertyTypeMapping.getIdMappings(); for (int j = 0, jlen = idMappings.length; j < jlen; j++) { ClassPropertyMetaDataMapping idMapping = (ClassPropertyMetaDataMapping) idMappings[j]; try { // initiaize the value in case it is lazy (and only for the first time) if (j == 0) { if (propertyValue instanceof HibernateProxy) { propertyValue = ((HibernateProxy) propertyValue).getHibernateLazyInitializer() .getImplementation(); } } if (collection) { for (Iterator iter = ((Collection) propertyValue).iterator(); iter.hasNext();) { Object obj = iter.next(); Object id = idMapping.getGetter().get(obj); if (id == null) { dependencies.add(obj); } dependencies.addAll( getUnpersistedCascades(compassGps, obj, sessionFactory, cascade, visited)); } } else { Object id = idMapping.getGetter().get(propertyValue); if (id == null) { dependencies.add(propertyValue); } dependencies.addAll(getUnpersistedCascades(compassGps, propertyValue, sessionFactory, cascade, visited)); } } catch (Exception e) { // ignore } } } return dependencies; }
From source file:org.nextframework.persistence.PersistenceUtils.java
License:Apache License
public static InverseCollectionProperties getInverseCollectionProperty(SessionFactory sessionFactory, Class<? extends Object> clazz, String collectionProperty) { SessionFactoryImplementor sessionFactoryImplementor; String[] keyColumnNames;//from w ww .ja va 2s.c om Class<?> returnedClass; try { sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory; ClassMetadata classMetadata = getClassMetadata(clazz, sessionFactory); if (classMetadata == null) { throw new PersistenceException("Class " + clazz.getName() + " is not mapped. "); } CollectionType ct = (CollectionType) classMetadata.getPropertyType(collectionProperty); AbstractCollectionPersister collectionMetadata = (AbstractCollectionPersister) sessionFactoryImplementor .getCollectionMetadata(ct.getRole()); keyColumnNames = ((AbstractCollectionPersister) collectionMetadata).getKeyColumnNames(); returnedClass = ct.getElementType(sessionFactoryImplementor).getReturnedClass(); } catch (ClassCastException e) { throw new PersistenceException( "Property \"" + collectionProperty + "\" of " + clazz + " is not a mapped as a collection."); } AbstractEntityPersister collectionItemMetadata = (AbstractEntityPersister) sessionFactoryImplementor .getClassMetadata(returnedClass); Type[] propertyTypes = collectionItemMetadata.getPropertyTypes(); String[] propertyNames = collectionItemMetadata.getPropertyNames(); for (int i = 0; i < propertyTypes.length; i++) { Type type = propertyTypes[i]; String propertyName = propertyNames[i]; String[] propertyColumnNames = collectionItemMetadata.getPropertyColumnNames(propertyName); InverseCollectionProperties inverseCollectionProperties = getInverseCollectionProperties( sessionFactoryImplementor, clazz, returnedClass, keyColumnNames, propertyColumnNames, type, propertyName); if (inverseCollectionProperties != null) { return inverseCollectionProperties; } } //check id Type identifierType = collectionItemMetadata.getIdentifierType(); String identifierName = collectionItemMetadata.getIdentifierPropertyName(); String[] identifierColumnNames = collectionItemMetadata.getIdentifierColumnNames(); InverseCollectionProperties inverseCollectionProperties = getInverseCollectionProperties( sessionFactoryImplementor, clazz, returnedClass, keyColumnNames, identifierColumnNames, identifierType, identifierName); if (inverseCollectionProperties != null) { return inverseCollectionProperties; } throw new PersistenceException( "Collection " + collectionProperty + " of " + clazz + " does not have an inverse path!"); }
From source file:org.openeos.services.dictionary.internal.HibernateAnnotationsMixedDictionaryService.java
License:Apache License
private IPropertyDefinition createPropertyDefinition(String propertyName, Type propertyType, ClassMetadata metaData) {//from w w w. j ava 2 s. c o m IPropertyDefinition propertyDef; if (propertyType.isCollectionType()) { CollectionType colType = (CollectionType) propertyType; CollectionMetadata colMetaData = sessionFactory.getCollectionMetadata(colType.getRole()); propertyDef = new HibernateAnnotationsMixedCollectionPropertyDefinitionImpl(metaData, propertyName, colMetaData); } else { propertyDef = new HibernateAnnotationsMixedPropertyDefinitionImpl(metaData, propertyName); } return propertyDef; }
From source file:org.openmrs.module.auditlog.api.db.DAOUtils.java
License:Open Source License
/** * Finds all the types for associations to audit in as recursive way i.e if a Persistent type is * found, then we also find its collection element types and types for fields mapped as one to * one.// w w w .j ava2 s. c o m * * @param clazz the Class to match against * @param foundAssocTypes the found association types * @return a set of found class names */ private static Set<Class<?>> getAssociationTypesToAuditInternal(Class<?> clazz, Set<Class<?>> foundAssocTypes) { if (foundAssocTypes == null) { foundAssocTypes = new HashSet<Class<?>>(); } ClassMetadata cmd = getSessionFactory().getClassMetadata(clazz); if (cmd != null) { for (Type type : cmd.getPropertyTypes()) { //If this is a OneToOne or a collection type if (type.isCollectionType() || OneToOneType.class.isAssignableFrom(type.getClass())) { CollectionType collType = (CollectionType) type; boolean isManyToManyColl = false; if (collType.isCollectionType()) { collType = (CollectionType) type; isManyToManyColl = ((SessionFactoryImplementor) getSessionFactory()) .getCollectionPersister(collType.getRole()).isManyToMany(); } Class<?> assocType = type.getReturnedClass(); if (type.isCollectionType()) { assocType = collType.getElementType((SessionFactoryImplementor) getSessionFactory()) .getReturnedClass(); } //Ignore non persistent types if (getSessionFactory().getClassMetadata(assocType) == null) { continue; } if (!foundAssocTypes.contains(assocType)) { //Don't implicitly audit types for many to many collections items if (!type.isCollectionType() || (type.isCollectionType() && !isManyToManyColl)) { foundAssocTypes.add(assocType); //Recursively inspect each association type foundAssocTypes.addAll(getAssociationTypesToAuditInternal(assocType, foundAssocTypes)); } } } } } return foundAssocTypes; }