List of usage examples for org.hibernate.type Type isAssociationType
boolean isAssociationType();
From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaEntity.java
License:Open Source License
/** * Read all the properties from Hibernate metadata */// www . j ava 2s . co m private void loadAllProperties() { if (allPropsRetrieved) return; synchronized (this) { if (!allPropsRetrieved) { metaAttributes = new HashMap<String, MetaAttribute>(); metaRoles = new HashMap<String, MetaRole>(); ClassMetadata meta = persister.getClassMetadata(); String[] propNames = meta.getPropertyNames(); for (String propName : propNames) { Type type; try { type = persister.getClassMetadata().getPropertyType(propName); } catch (QueryException ex) { throw new RuntimeException("Unable to determine type for property " + propName + " of entity " + persister.getEntityName()); } if (type.isComponentType()) { // Do nothing } else if (type.isCollectionType() || type.isEntityType() || type.isAssociationType()) { boolean isParentToChild = type.isCollectionType(); MetaRole mr = new HibMetaRole(this, propName, isParentToChild); metaRoles.put(propName, mr); } else { MetaAttribute ma = new HibMetaAttribute(propName, type.getReturnedClass(), false); metaAttributes.put(propName, ma); } } // Often the primary attribute(s) is not returned by ClassMetadata.getPropertyNames // So we add it by hand here String pkName = meta.getIdentifierPropertyName(); if (pkName == null) { // Can happen for composite keys Type pkType = meta.getIdentifierType(); if (pkType.isComponentType()) { ComponentType ctype = (ComponentType) pkType; String[] pnames = ctype.getPropertyNames(); for (String pname : pnames) { MetaAttribute ma = new HibMetaAttribute(pname, meta.getPropertyType(pname).getReturnedClass(), false); metaAttributes.put(pname, ma); } } else throw new RuntimeException( "Unexpected: anonymous PK is not composite - class " + meta.getEntityName()); } else if (!metaAttributes.containsKey(pkName)) { MetaAttribute ma = new HibMetaAttribute(pkName, meta.getIdentifierType().getReturnedClass(), false); metaAttributes.put(pkName, ma); } allPropsRetrieved = true; } } }
From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java
License:Open Source License
/** * Translate a relative path expression into a Hibernate relative path * /*from w w w . j av a 2 s. c om*/ * @param rpe * @param hStep */ protected HibernateRelativePath process(RelativePathExpr rpe, HibernateStep context) { logger.debug("Processing relative path [{}]", rpe.getXPath()); HibernateRelativePath hRPath = new HibernateRelativePath(); hRPath.setContext(context); /** * Offset to the first step after the context step if the relative path * is an absolute. Assumption is that absolute paths are grounds for the * start of a Hibernate criteria. */ int contextDepth = 0; if (rpe.getFirstExpr().getType() == Expr.Type.Root) { logger.debug("Offsetting processing by 2 adding the passed context [{}] as the first Hibernate step", context); contextDepth = 2; hRPath.setAbsolute(true); hRPath.getHiberateSteps().add(context); } /** * Process each step. Non absolute relative paths take their context * from the passed Hibernate step (likely predicate expressions). */ for (int depth = contextDepth; depth < rpe.getDepth(); depth++) { Step step = (Step) rpe.getExpr(depth); switch (step.getType()) { case Step: if (hRPath.getHiberateSteps().size() > 0) context = hRPath.getLastHibernateStep(); CIBean bean = context.getCIBean(); ClassMetadata cm = session.getSessionFactory().getClassMetadata(bean.getJavaClass()); String property = step.getQName().getLocalPart(); org.hibernate.type.Type propertyType = getPropertyType(cm, property); if (propertyType == null) throw new ApplicationException( String.format("Step [%s] not defined as a property to the Hibernate context [%s]", step, cm.getEntityName())); HibernateStep hStep = new HibernateStep(); hStep.setStep(step); hStep.setName(property); hStep.setPath(String.format("%s.%s", context.getPath(), property)); /** * Type */ if (propertyType.isEntityType()) hStep.setType(Type.Entity); if (propertyType.isAssociationType()) hStep.setType(Type.Association); /** * Store the CIBean corresponding to the property by type not * name. Store as well the alias. */ if (hStep.getType() != Type.Property) { CIProperty prop = bean.getPropertyByName(step.getQName()); /** * Does the property have corresponding CI Bean? */ CIBean other = ciContext.getBean(prop.getType()); if (other == null) throw new ApplicationException( String.format("Step [%s] has no corresponding CI Bean metadata", step)); hStep.setCIBean(other); } if (propertyType.getName().equals(JAXBUserType.class.getName())) { hStep.setXml(true); if (step.getNext() != null) hRPath.setTruncated(true); } /** * Connect together the Hibernate steps */ if (hRPath.getHiberateSteps().size() > 0) { HibernateStep last = hRPath.getLastHibernateStep(); last.setNext(hStep); hStep.setPrevious(last); } /** * Make sure the PathExpression is stored */ hStep.setBaseExpression(context.getBaseExpression()); /** * Add the Hibernate step */ hRPath.getHiberateSteps().add(hStep); break; case Root: throw new ApplicationException(String .format("Only resolute steps valid [Root encountered at depth: %d]", step.getDepth())); case Irresolute: throw new ApplicationException( String.format("Only resolute steps valid [Irresolute encountered at depth: %d]", depth)); default: throw new ApplicationException(String .format(String.format("Undefined expression type [%s] at depth", step.getType(), depth))); } if (hRPath.getLastHibernateStep().getType() == Type.Property) break; } logger.debug("Hibernate relative path: {}", hRPath); return hRPath; }
From source file:com.miranteinfo.seam.hibernate.HibernateCascade.java
License:Open Source License
/** * Cascade an action to the child or children */// ww w . ja v a2s.c o m private void cascadeProperty(final Object child, final Type type, final CascadeStyle style, final Object anything, final boolean isCascadeDeleteEnabled) throws HibernateException { if (child != null) { if (type.isAssociationType()) { AssociationType associationType = (AssociationType) type; if (cascadeAssociationNow(associationType)) { cascadeAssociation(child, type, style, anything, isCascadeDeleteEnabled); } } else if (type.isComponentType()) { cascadeComponent(child, (AbstractComponentType) type, anything); } } }
From source file:com.reignite.parser.Join.java
License:Open Source License
/** * Gets all the basic fields of the criteria entity * /*w ww . jav a 2s . c om*/ * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IntrospectionException */ public void populateFields() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IntrospectionException { Class<?> clazz = Class.forName(entity); Method getter = clazz.getMethod("get" + Character.toUpperCase(name.charAt(0)) + name.substring(1)); Class<?> joined = (Class<?>) ((ParameterizedType) getter.getGenericReturnType()) .getActualTypeArguments()[0]; ClassMetadata metadata = session.getSessionFactory().getClassMetadata(joined); expectedFields.add(name + "." + metadata.getIdentifierPropertyName()); projections.add(Projections.property(name + "." + metadata.getIdentifierPropertyName())); for (String fieldName : metadata.getPropertyNames()) { Type type = metadata.getPropertyType(fieldName); if (!type.isAnyType() && !type.isAssociationType() && !type.isComponentType() && !type.isCollectionType()) { String field = name + "." + fieldName; expectedFields.add(field); projections.add(Projections.property(field)); } } }
From source file:com.siemens.scr.avt.ad.query.common.DicomMappingDictionaryLoadingStrategy.java
License:Open Source License
private void loadProperty(DicomMappingDictionary dict, Property prop, Table table, String classPrefix) { String key = classPrefix + "." + prop.getName(); Type type = prop.getType(); String tableName = table.getSchema() + "." + table.getName(); if (type.isAssociationType() || type.isCollectionType()) { // do nothing } else if (type.isComponentType()) { Component component = (Component) prop.getValue(); Iterator<Property> it = component.getPropertyIterator(); while (it.hasNext()) { Property subProp = it.next(); loadProperty(dict, subProp, table, component.getRoleName()); }/* w w w .jav a2s . c o m*/ } else { int sqltype = sqlTypes(type); assert prop.getColumnSpan() == 1; Iterator<Column> it = prop.getColumnIterator(); String column = it.next().getName(); dict.addMappingEntry(key, tableName, column, sqltype); loadTag(dict, prop, key); loadDicomHeaderMetadata(dict, tableName, column, prop); } }
From source file:corner.orm.hibernate.expression.NewExpressionExample.java
License:Apache License
private boolean isPropertyIncluded(Object value, String name, Type type) { return !excludedProperties.contains(name) && !type.isAssociationType() && selector.include(value, name, type); }
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 ava 2 s . co 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:gov.nih.nci.calims2.business.report.query.MetadataServiceImpl.java
License:BSD License
/** * Process a given property for the descriptor construction. * @param descriptor The descriptor under construction * @param prefix The property prefix (in case of component properties) * @param name The property name// w ww . ja v a 2s.c om * @param type The property type * @param excludeRelationship true if relationship must not be extracted */ void processProperty(EntityDescriptor descriptor, String prefix, String name, Type type, boolean excludeRelationship) { if (type.isAssociationType()) { if (excludeRelationship) { return; } if (!type.isCollectionType()) { RelationshipDescriptor rd = new RelationshipDescriptor(); rd.setName(name); Class<?> relatedClass; try { relatedClass = Class.forName(type.getName()); } catch (ClassNotFoundException e) { throw new InternalError("Should not happern. Hibernate is initialized correctly at this point"); } rd.setPersistentClass(relatedClass); EntityDescriptor relatedClassDescriptor = getEntityDescriptor(relatedClass, true); rd.setProperties(relatedClassDescriptor.getProperties()); Collections.sort(rd.getProperties()); descriptor.addRelationship(rd); } } else { if (type.isComponentType()) { ComponentType componentType = (ComponentType) type; String[] propertyNames = componentType.getPropertyNames(); Type[] types = componentType.getSubtypes(); String newPrefix = prefix + name + "."; for (int i = 0; i < propertyNames.length; i++) { processProperty(descriptor, newPrefix, propertyNames[i], types[i], false); } } else { if (!type.isCollectionType()) { PropertyDescriptor property = new PropertyDescriptor(); property.setName(prefix + name); property.setType(type.getName()); property.setReturnedClass(type.getReturnedClass()); descriptor.addProperty(property); } } } }
From source file:grails.orm.HibernateCriteriaBuilder.java
License:Apache License
@SuppressWarnings("rawtypes") @Override/*from ww w . j a va 2 s . co m*/ public Object invokeMethod(String name, Object obj) { Object[] args = obj.getClass().isArray() ? (Object[]) obj : new Object[] { obj }; if (paginationEnabledList && SET_RESULT_TRANSFORMER_CALL.equals(name) && args.length == 1 && args[0] instanceof ResultTransformer) { resultTransformer = (ResultTransformer) args[0]; return null; } if (isCriteriaConstructionMethod(name, args)) { if (criteria != null) { throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here")); } if (name.equals(GET_CALL)) { uniqueResult = true; } else if (name.equals(SCROLL_CALL)) { scroll = true; } else if (name.equals(COUNT_CALL)) { count = true; } else if (name.equals(LIST_DISTINCT_CALL)) { resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY; } createCriteriaInstance(); // Check for pagination params if (name.equals(LIST_CALL) && args.length == 2) { paginationEnabledList = true; orderEntries = new ArrayList<Order>(); invokeClosureNode(args[1]); } else { invokeClosureNode(args[0]); } if (resultTransformer != null) { criteria.setResultTransformer(resultTransformer); } Object result; if (!uniqueResult) { if (scroll) { result = criteria.scroll(); } else if (count) { criteria.setProjection(Projections.rowCount()); result = criteria.uniqueResult(); } else if (paginationEnabledList) { // Calculate how many results there are in total. This has been // moved to before the 'list()' invocation to avoid any "ORDER // BY" clause added by 'populateArgumentsForCriteria()', otherwise // an exception is thrown for non-string sort fields (GRAILS-2690). criteria.setFirstResult(0); criteria.setMaxResults(Integer.MAX_VALUE); criteria.setProjection(Projections.rowCount()); int totalCount = ((Number) criteria.uniqueResult()).intValue(); // Restore the previous projection, add settings for the pagination parameters, // and then execute the query. if (projectionList != null && projectionList.getLength() > 0) { criteria.setProjection(projectionList); } else { criteria.setProjection(null); } for (Order orderEntry : orderEntries) { criteria.addOrder(orderEntry); } if (resultTransformer == null) { criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } else if (paginationEnabledList) { // relevant to GRAILS-5692 criteria.setResultTransformer(resultTransformer); } // GRAILS-7324 look if we already have association to sort by Map argMap = (Map) args[0]; final String sort = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_SORT); if (sort != null) { boolean ignoreCase = true; Object caseArg = argMap.get(GrailsHibernateUtil.ARGUMENT_IGNORE_CASE); if (caseArg instanceof Boolean) { ignoreCase = (Boolean) caseArg; } final String orderParam = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_ORDER); final String order = GrailsHibernateUtil.ORDER_DESC.equalsIgnoreCase(orderParam) ? GrailsHibernateUtil.ORDER_DESC : GrailsHibernateUtil.ORDER_ASC; int lastPropertyPos = sort.lastIndexOf('.'); String associationForOrdering = lastPropertyPos >= 0 ? sort.substring(0, lastPropertyPos) : null; if (associationForOrdering != null && aliasMap.containsKey(associationForOrdering)) { addOrder(criteria, aliasMap.get(associationForOrdering) + "." + sort.substring(lastPropertyPos + 1), order, ignoreCase); // remove sort from arguments map to exclude from default processing. @SuppressWarnings("unchecked") Map argMap2 = new HashMap(argMap); argMap2.remove(GrailsHibernateUtil.ARGUMENT_SORT); argMap = argMap2; } } GrailsHibernateUtil.populateArgumentsForCriteria(grailsApplication, targetClass, criteria, argMap); PagedResultList pagedRes = new PagedResultList(criteria.list()); // Updated the paged results with the total number of records calculated previously. pagedRes.setTotalCount(totalCount); result = pagedRes; } else { result = criteria.list(); } } else { result = GrailsHibernateUtil.unwrapIfProxy(criteria.uniqueResult()); } if (!participate) { hibernateSession.close(); } return result; } if (criteria == null) createCriteriaInstance(); MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args); if (metaMethod != null) { return metaMethod.invoke(this, args); } metaMethod = criteriaMetaClass.getMetaMethod(name, args); if (metaMethod != null) { return metaMethod.invoke(criteria, args); } metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args); if (metaMethod != null) { return metaMethod.invoke(criteria, args); } if (isAssociationQueryMethod(args) || isAssociationQueryWithJoinSpecificationMethod(args)) { final boolean hasMoreThanOneArg = args.length > 1; Object callable = hasMoreThanOneArg ? args[1] : args[0]; int joinType = hasMoreThanOneArg ? (Integer) args[0] : CriteriaSpecification.INNER_JOIN; if (name.equals(AND) || name.equals(OR) || name.equals(NOT)) { if (criteria == null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } logicalExpressionStack.add(new LogicalExpression(name)); invokeClosureNode(callable); LogicalExpression logicalExpression = logicalExpressionStack .remove(logicalExpressionStack.size() - 1); addToCriteria(logicalExpression.toCriterion()); return name; } if (name.equals(PROJECTIONS) && args.length == 1 && (args[0] instanceof Closure)) { if (criteria == null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } projectionList = Projections.projectionList(); invokeClosureNode(callable); if (projectionList != null && projectionList.getLength() > 0) { criteria.setProjection(projectionList); } return name; } final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetClass, name); if (pd != null && pd.getReadMethod() != null) { ClassMetadata meta = sessionFactory.getClassMetadata(targetClass); Type type = meta.getPropertyType(name); if (type.isAssociationType()) { String otherSideEntityName = ((AssociationType) type) .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); Class oldTargetClass = targetClass; targetClass = sessionFactory.getClassMetadata(otherSideEntityName) .getMappedClass(EntityMode.POJO); if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) { joinType = CriteriaSpecification.LEFT_JOIN; // default to left join if joining on the same table } associationStack.add(name); final String associationPath = getAssociationPath(); createAliasIfNeccessary(name, associationPath, joinType); // the criteria within an association node are grouped with an implicit AND logicalExpressionStack.add(new LogicalExpression(AND)); invokeClosureNode(callable); aliasStack.remove(aliasStack.size() - 1); if (!aliasInstanceStack.isEmpty()) { aliasInstanceStack.remove(aliasInstanceStack.size() - 1); } LogicalExpression logicalExpression = logicalExpressionStack .remove(logicalExpressionStack.size() - 1); if (!logicalExpression.args.isEmpty()) { addToCriteria(logicalExpression.toCriterion()); } associationStack.remove(associationStack.size() - 1); targetClass = oldTargetClass; return name; } } } else if (args.length == 1 && args[0] != null) { if (criteria == null) { throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here")); } Object value = args[0]; Criterion c = null; if (name.equals(ID_EQUALS)) { return eq("id", value); } if (name.equals(IS_NULL) || name.equals(IS_NOT_NULL) || name.equals(IS_EMPTY) || name.equals(IS_NOT_EMPTY)) { if (!(value instanceof String)) { throwRuntimeException(new IllegalArgumentException( "call to [" + name + "] with value [" + value + "] requires a String value.")); } String propertyName = calculatePropertyName((String) value); if (name.equals(IS_NULL)) { c = Restrictions.isNull(propertyName); } else if (name.equals(IS_NOT_NULL)) { c = Restrictions.isNotNull(propertyName); } else if (name.equals(IS_EMPTY)) { c = Restrictions.isEmpty(propertyName); } else if (name.equals(IS_NOT_EMPTY)) { c = Restrictions.isNotEmpty(propertyName); } } if (c != null) { return addToCriteria(c); } } throw new MissingMethodException(name, getClass(), args); }
From source file:org.broadleafcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider.java
License:Apache License
@Override public FieldProviderResponse addMetadata(AddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) { Map<String, Object> idMetadata = addMetadataRequest.getDynamicEntityDao() .getIdMetadata(addMetadataRequest.getTargetClass()); if (idMetadata != null) { String idField = (String) idMetadata.get("name"); boolean processField; //allow id fields without AdminPresentation annotation to pass through processField = idField.equals(addMetadataRequest.getRequestedField().getName()); if (!processField) { List<String> propertyNames = addMetadataRequest.getDynamicEntityDao() .getPropertyNames(addMetadataRequest.getTargetClass()); if (!CollectionUtils.isEmpty(propertyNames)) { List<org.hibernate.type.Type> propertyTypes = addMetadataRequest.getDynamicEntityDao() .getPropertyTypes(addMetadataRequest.getTargetClass()); int index = propertyNames.indexOf(addMetadataRequest.getRequestedField().getName()); if (index >= 0) { Type myType = propertyTypes.get(index); //allow OneToOne, ManyToOne and Embeddable fields to pass through processField = myType.isCollectionType() || myType.isAssociationType() || myType.isComponentType() || myType.isEntityType(); }/*from w ww . j a v a 2s . co m*/ } } if (processField) { FieldInfo info = buildFieldInfo(addMetadataRequest.getRequestedField()); BasicFieldMetadata basicMetadata = new BasicFieldMetadata(); basicMetadata.setName(addMetadataRequest.getRequestedField().getName()); basicMetadata.setExcluded(false); metadata.put(addMetadataRequest.getRequestedField().getName(), basicMetadata); setClassOwnership(addMetadataRequest.getParentClass(), addMetadataRequest.getTargetClass(), metadata, info); return FieldProviderResponse.HANDLED; } } return FieldProviderResponse.NOT_HANDLED; }