List of usage examples for org.hibernate.type CollectionType getElementType
public final Type getElementType(SessionFactoryImplementor factory) throws MappingException
From source file:be.shad.tsqb.helper.TypeSafeQueryHelperImpl.java
License:Apache License
/** * Retrieves the type information from hibernate. *//*from w w w . j ava2 s. c o m*/ private Class<?> getTargetEntityClass(Type propertyType) { if (CollectionType.class.isAssignableFrom(propertyType.getClass())) { CollectionType collectionType = (CollectionType) propertyType; Type elementType = collectionType.getElementType((SessionFactoryImplementor) sessionFactory); return elementType.getReturnedClass(); } return propertyType.getReturnedClass(); }
From source file:com.autobizlogic.abl.mgmt.ClassMetadataService.java
License:Open Source License
public static Map<String, Object> getMetadataForClass(Map<String, String> args) { String sessionFactoryId = args.get("sessionFactoryId"); String name = args.get("className"); HashMap<String, Object> result = new HashMap<String, Object>(); SessionFactory factory = HibernateConfiguration.getSessionFactoryById(sessionFactoryId); if (factory == null) return null; ClassMetadata meta = factory.getClassMetadata(name); if (meta == null) return null; result.put("sessionFactoryId", sessionFactoryId); result.put("className", meta.getEntityName()); result.put("identifierPropertyName", meta.getIdentifierPropertyName()); Class<?> cls = meta.getMappedClass(EntityMode.POJO); Class<?> supercls = cls.getSuperclass(); while (ProxyFactory.isProxyClass(supercls)) supercls = supercls.getSuperclass(); result.put("superclassName", supercls.getName()); Map<String, String> properties = new HashMap<String, String>(); Map<String, Object> collections = new HashMap<String, Object>(); Map<String, String> associations = new HashMap<String, String>(); String[] propNames = meta.getPropertyNames(); Type[] propTypes = meta.getPropertyTypes(); int i = 0;/* w w w .ja va 2 s . c o m*/ for (String propName : propNames) { if (propTypes[i].isCollectionType()) { CollectionType collType = (CollectionType) propTypes[i]; Type elementType = collType.getElementType((SessionFactoryImplementor) factory); HashMap<String, String> collEntry = new HashMap<String, String>(); collEntry.put("collectionType", collType.getReturnedClass().getName()); collEntry.put("elementType", elementType.getName()); collections.put(propName, collEntry); } else if (propTypes[i].isAssociationType()) { AssociationType assType = (AssociationType) propTypes[i]; String assName = assType.getAssociatedEntityName((SessionFactoryImplementor) factory); associations.put(propName, assName); } else { properties.put(propName, propTypes[i].getName()); } i++; } result.put("properties", properties); result.put("associations", associations); result.put("collections", collections); MetaModel metaModel = MetaModelFactory.getHibernateMetaModel(factory); LogicGroup logicGroup = RuleManager.getInstance(metaModel).getLogicGroupForClassName(name); if (logicGroup != null) { // Operations are actually actions and constraints List<Map<String, Object>> operations = new Vector<Map<String, Object>>(); result.put("operations", operations); Set<ActionRule> actions = logicGroup.getActions(); if (actions != null && actions.size() > 0) { for (ActionRule a : actions) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", a.getLogicMethodName()); op.put("type", "action"); operations.add(op); } } Set<EarlyActionRule> eactions = logicGroup.getEarlyActions(); if (eactions != null && eactions.size() > 0) { for (EarlyActionRule a : eactions) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", a.getLogicMethodName()); op.put("type", "early action"); operations.add(op); } } Set<CommitActionRule> cactions = logicGroup.getCommitActions(); if (cactions != null && cactions.size() > 0) { for (CommitActionRule a : cactions) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", a.getLogicMethodName()); op.put("type", "commit action"); operations.add(op); } } Set<ConstraintRule> constraints = logicGroup.getConstraints(); if (constraints != null && constraints.size() > 0) { for (ConstraintRule constraint : constraints) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", constraint.getLogicMethodName()); op.put("type", "constraint"); operations.add(op); } } Set<CommitConstraintRule> cconstraints = logicGroup.getCommitConstraints(); if (cconstraints != null && cconstraints.size() > 0) { for (ConstraintRule cconstraint : cconstraints) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", cconstraint.getLogicMethodName()); op.put("type", "commit constraint"); operations.add(op); } } // Derivations are derived attributes Map<String, Object> derivations = new HashMap<String, Object>(); result.put("derivations", derivations); Set<AbstractAggregateRule> aggregates = logicGroup.getAggregates(); if (aggregates != null && aggregates.size() > 0) { for (AbstractAggregateRule aggregate : aggregates) { Map<String, Object> agg = new HashMap<String, Object>(); if (aggregate instanceof CountRule) agg.put("type", "count"); else if (aggregate instanceof SumRule) agg.put("type", "sum"); else agg.put("type", "unknown"); agg.put("methodName", aggregate.getLogicMethodName()); derivations.put(aggregate.getBeanAttributeName(), agg); } } List<FormulaRule> formulas = logicGroup.getFormulas(); if (formulas != null && formulas.size() > 0) { for (FormulaRule formula : formulas) { Map<String, Object> form = new HashMap<String, Object>(); form.put("type", "formula"); form.put("methodName", formula.getLogicMethodName()); derivations.put(formula.getBeanAttributeName(), form); } } Set<ParentCopyRule> pcRules = logicGroup.getParentCopies(); if (pcRules != null && pcRules.size() > 0) { for (ParentCopyRule pcRule : pcRules) { Map<String, Object> parentCopy = new HashMap<String, Object>(); parentCopy.put("type", "parent copy"); parentCopy.put("methodName", pcRule.getLogicMethodName()); derivations.put(pcRule.getChildAttributeName(), parentCopy); } } } HashMap<String, Object> finalResult = new HashMap<String, Object>(); finalResult.put("data", result); return finalResult; }
From source file:com.miranteinfo.seam.hibernate.HibernateCascade.java
License:Open Source License
/** * Cascade to the collection elements//from ww w . ja v a 2 s.com */ 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:org.atemsource.atem.impl.hibernate.attributetype.MultiAssociationAttributeType.java
License:Apache License
@Override public Attribute create(final ValidationMetaData validationMetaData, final EntityType entityType, final HibernateEntityTypeCreationContext ctx, final PropertyDescriptor propertyDescriptor, final Type attributeType, final SessionFactoryImplementor sessionFactoryImplementor) { CollectionType listType = (CollectionType) attributeType; Type elementType = listType.getElementType(sessionFactoryImplementor); EntityType elementEntityType = ctx//from w w w . j a va 2s .c om .getEntityTypeReference(((org.hibernate.type.EntityType) elementType).getAssociatedEntityName()); AbstractCollectionAttributeImpl attribute; if (listType instanceof ListType || listType instanceof BagType) { attribute = create(ListAttributeImpl.class); } else if (listType instanceof SetType) { attribute = create(SetAttributeImpl.class); } else { throw new IllegalStateException("unknown type " + attributeType.getName()); } setStandardProperties(entityType, propertyDescriptor, attribute); Association association = propertyDescriptor.getAnnotation(Association.class); attribute.setAccessor(new HibernateAccessor(propertyDescriptor.getField(), propertyDescriptor.getReadMethod(), propertyDescriptor.getWriteMethod())); attribute.setTargetType(elementEntityType); return attribute; }
From source file:org.atemsource.atem.impl.hibernate.attributetype.MultiCompositionAttributeType.java
License:Apache License
@Override public Attribute create(final ValidationMetaData validationMetaData, final EntityType entityType, final HibernateEntityTypeCreationContext ctx, final PropertyDescriptor propertyDescriptor, final Type attributeType, final SessionFactoryImplementor sessionFactoryImplementor) { CollectionType listType = (CollectionType) attributeType; Type elementType = listType.getElementType(sessionFactoryImplementor); EntityType elementEntityType = ctx.createComponentType((ComponentType) elementType); Set<EntityType> validTypesSet = createValidtypesSet(elementEntityType, null, null, ctx); AbstractCollectionAttributeImpl attribute; if (listType instanceof ListType || listType instanceof BagType) { attribute = create(ListAttributeImpl.class); } else if (listType instanceof SetType) { attribute = create(SetAttributeImpl.class); } else {//from www.java2 s. c om throw new IllegalStateException("unknown type " + attributeType.getName()); } setStandardProperties(entityType, propertyDescriptor, attribute); attribute.setTargetType(elementEntityType); attribute.setAccessor(new HibernateAccessor(propertyDescriptor.getField(), propertyDescriptor.getReadMethod(), propertyDescriptor.getWriteMethod())); return attribute; }
From source file:org.atemsource.atem.impl.hibernate.attributetype.PrimitiveCollectionAttributeType.java
License:Apache License
@Override public Attribute create(ValidationMetaData validationMetaData, EntityType entityType, HibernateEntityTypeCreationContext ctx, PropertyDescriptor propertyDescriptor, Type attributeType, SessionFactoryImplementor sessionFactoryImplementor) { CollectionType collectionType = (CollectionType) attributeType; Class<?> propertyType = propertyDescriptor.getPropertyType(); AbstractAttribute attribute;/*from ww w .j a va2 s.co m*/ if (List.class.isAssignableFrom(propertyType)) { attribute = beanCreator.create(ListAttributeImpl.class); } else if (Set.class.isAssignableFrom(propertyType)) { attribute = beanCreator.create(SetAttributeImpl.class); } else if (Collection.class.isAssignableFrom(propertyType)) { attribute = beanCreator.create(CollectionAttributeImpl.class); } else { throw new IllegalStateException( "properyType " + propertyType.getName() + " cannot be used for multi associations"); } Type elementType = collectionType.getElementType(sessionFactoryImplementor); PrimitiveType primitiveType = primitiveTypeFactory.getPrimitiveType(elementType.getReturnedClass()); ((AbstractCollectionAttributeImpl) attribute).setTargetType(primitiveType); setStandardProperties(entityType, propertyDescriptor, attribute); ((AbstractCollectionAttributeImpl) attribute).setAccessor(new PojoAccessor(propertyDescriptor.getField(), propertyDescriptor.getReadMethod(), propertyDescriptor.getWriteMethod(), false)); return attribute; }
From source file:org.geomajas.layer.hibernate.HibernateLayerUtil.java
License:Open Source License
/** * Return the class of one of the properties of another class from which the Hibernate metadata is given. * // www . j av a 2 s . c om * @param meta * The parent class to search a property in. * @param propertyName * The name of the property in the parent class (provided by meta) * @return Returns the class of the property in question. * @throws HibernateLayerException * Throws an exception if the property name could not be retrieved. */ protected Class<?> getPropertyClass(ClassMetadata meta, String propertyName) throws HibernateLayerException { // try to assure the correct separator is used propertyName = propertyName.replace(XPATH_SEPARATOR, SEPARATOR); if (propertyName.contains(SEPARATOR)) { String directProperty = propertyName.substring(0, propertyName.indexOf(SEPARATOR)); try { Type prop = meta.getPropertyType(directProperty); if (prop.isCollectionType()) { CollectionType coll = (CollectionType) prop; prop = coll.getElementType((SessionFactoryImplementor) sessionFactory); } ClassMetadata propMeta = sessionFactory.getClassMetadata(prop.getReturnedClass()); return getPropertyClass(propMeta, propertyName.substring(propertyName.indexOf(SEPARATOR) + 1)); } catch (HibernateException e) { throw new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName, meta.getEntityName()); } } else { try { return meta.getPropertyType(propertyName).getReturnedClass(); } catch (HibernateException e) { throw new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName, meta.getEntityName()); } } }
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;//w ww .j a va 2 s. co m 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.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./*from w ww. j a v a 2s. c om*/ * * @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; }
From source file:org.riotfamily.media.cleanup.HibernateCleanUpTask.java
License:Apache License
@SuppressWarnings("unchecked") private void init() { Collection<ClassMetadata> allMeta = getSessionFactory().getAllClassMetadata().values(); for (ClassMetadata meta : allMeta) { for (String name : meta.getPropertyNames()) { Type type = meta.getPropertyType(name); if (RiotFile.class.isAssignableFrom(type.getReturnedClass())) { fileQueries.add(String.format("select %1$s.id from %2$s where %1$s is not null", name, meta.getEntityName())); } else if (type instanceof ComponentType) { handleComponentType((ComponentType) type, name, meta.getEntityName()); } else if (type instanceof CollectionType) { CollectionType collectionType = (CollectionType) type; Type elementType = collectionType .getElementType((SessionFactoryImplementor) getSessionFactory()); if (RiotFile.class.isAssignableFrom(elementType.getReturnedClass())) { fileQueries.add(String.format( "select file.id from %1$s ref " + "join ref.%2$s as file where file is not null", meta.getEntityName(), name)); } else if (elementType instanceof ComponentType) { handleCollectionComponentType((ComponentType) elementType, null, name, meta.getEntityName()); }/*from w w w . j a va 2 s . co m*/ } } } }