List of usage examples for javax.persistence.metamodel SingularAttribute getBindableJavaType
Class<T> getBindableJavaType();
From source file:com.impetus.kundera.utils.KunderaCoreUtils.java
/** * Prepares composite key as a lucene key. * /*from w w w .j a va 2 s . c o m*/ * @param m * entity metadata * @param metaModel * meta model. * @param compositeKey * composite key instance * @return redis key */ public static String prepareCompositeKey(final SingularAttribute attribute, final MetamodelImpl metaModel, final Object compositeKey) { Field[] fields = attribute.getBindableJavaType().getDeclaredFields(); EmbeddableType embeddable = metaModel.embeddable(attribute.getBindableJavaType()); StringBuilder stringBuilder = new StringBuilder(); try { for (Field f : fields) { if (!ReflectUtils.isTransientOrStatic(f)) { if (metaModel.isEmbeddable( ((AbstractAttribute) embeddable.getAttribute(f.getName())).getBindableJavaType())) { f.setAccessible(true); stringBuilder.append( prepareCompositeKey((SingularAttribute) embeddable.getAttribute(f.getName()), metaModel, f.get(compositeKey))) .append(LUCENE_COMPOSITE_KEY_SEPERATOR); } else { String fieldValue = PropertyAccessorHelper.getString(compositeKey, f); fieldValue = fieldValue.replaceAll("[^a-zA-Z0-9]", "_"); stringBuilder.append(fieldValue); stringBuilder.append(LUCENE_COMPOSITE_KEY_SEPERATOR); } } } } catch (IllegalAccessException e) { logger.error(e.getMessage()); } catch (IllegalArgumentException e) { logger.error("Error during prepare composite key, Caused by {}.", e); throw new PersistenceException(e); } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(LUCENE_COMPOSITE_KEY_SEPERATOR)); } return stringBuilder.toString(); }
From source file:com.dbs.sdwt.jpa.ByExampleUtil.java
@SuppressWarnings("unchecked") public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne( ManagedType<T> mt, Root<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) { List<Predicate> predicates = newArrayList(); for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) { if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { M2O m2oValue = (M2O) jpaUtil.getValue(mtValue, mt.getAttribute(attr.getName())); Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType(); Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr); ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType); if (m2oValue != null) { if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId())); } else { predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder)); }// w ww . j av a 2 s. c o m } } } return predicates; }
From source file:com.impetus.client.cassandra.CassandraClientBase.java
/** * On where clause./*from w w w. j a v a2 s .c om*/ * * @param metadata * the metadata * @param key * the compound key object * @param translator * the translator * @param queryBuilder * the query builder * @param metaModel * the meta model * @param attribute * the attribute */ protected void onWhereClause(EntityMetadata metadata, Object key, CQLTranslator translator, StringBuilder queryBuilder, MetamodelImpl metaModel, SingularAttribute attribute) { // SingularAttribute idAttribute = metadata.getIdAttribute(); if (metaModel.isEmbeddable(attribute.getBindableJavaType())) { Field[] fields = attribute.getBindableJavaType().getDeclaredFields(); EmbeddableType compoundKey = metaModel.embeddable(attribute.getBindableJavaType()); for (Field field : fields) { if (field != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(Transient.class)) { attribute = (SingularAttribute) compoundKey.getAttribute(field.getName()); Object valueObject = PropertyAccessorHelper.getObject(key, field); if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) { onWhereClause(metadata, valueObject, translator, queryBuilder, metaModel, attribute); } else { String columnName = ((AbstractAttribute) attribute).getJPAColumnName(); translator.buildWhereClause(queryBuilder, field.getType(), columnName, valueObject, CQLTranslator.EQ_CLAUSE, false); } } } } else { translator.buildWhereClause(queryBuilder, ((AbstractAttribute) attribute).getBindableJavaType(), CassandraUtilities.getIdColumnName(kunderaMetadata, metadata, getExternalProperties(), isCql3Enabled(metadata)), key, translator.EQ_CLAUSE, false); } }
From source file:net.sf.gazpachoquest.qbe.ByExampleSpecification.java
public <T extends Persistable> Specification<T> byExampleOnEntity(final T example, final SearchParameters sp) { Validate.notNull(example, "example must not be null"); return new Specification<T>() { @Override// ww w . j a va 2 s .c o m public Predicate toPredicate(final Root<T> rootPath, final CriteriaQuery<?> query, final CriteriaBuilder builder) { Class<T> type = rootPath.getModel().getBindableJavaType(); ManagedType<T> mt = em.getMetamodel().entity(type); List<Predicate> predicates = new ArrayList<Predicate>(); predicates.addAll(byExample(mt, rootPath, example, sp, builder)); predicates.addAll(byExampleOnXToOne(mt, rootPath, example, sp, builder)); // 1 level deep only predicates.addAll(byExampleOnManyToMany(mt, rootPath, example, sp, builder)); // order by query.orderBy(JpaUtil.buildJpaOrders(sp.getOrders(), rootPath, builder)); return JpaUtil.andPredicate(builder, predicates); } //https://github.com/jaxio/generated-projects/tree/master/jsf2-spring-conversation/src/main/generated-java/com/jaxio/appli/repository/support public <T extends Persistable> List<Predicate> byExample(final ManagedType<T> mt, final Path<T> mtPath, final T mtValue, final SearchParameters sp, final CriteriaBuilder builder) { List<Predicate> predicates = new ArrayList<Predicate>(); for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) { if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE || attr.getPersistentAttributeType() == EMBEDDED || attr.getJavaType().isAssignableFrom(Map.class)) { continue; } Object attrValue = getValue(mtValue, attr); if (attrValue != null) { if (attr.getJavaType() == String.class) { if (isNotEmpty((String) attrValue)) { SingularAttribute<? super T, String> stringAttribute = mt .getSingularAttribute(attr.getName(), String.class); predicates.add(JpaUtil.stringPredicate(mtPath.get(stringAttribute), attrValue, sp, builder)); } } else { SingularAttribute<? super T, ?> attribute = mt.getSingularAttribute(attr.getName(), attr.getJavaType()); // apply equal predicates.add(builder.equal(mtPath.get(attribute), attrValue)); } } } return predicates; } /** * Construct a join predicate on collection (eg many to many, List) */ public <T extends Persistable> List<Predicate> byExampleOnManyToMany(final ManagedType<T> mt, final Root<T> mtPath, final T mtValue, final SearchParameters sp, final CriteriaBuilder builder) { List<Predicate> predicates = new ArrayList<Predicate>(); for (PluralAttribute<T, ?, ?> pa : mt.getDeclaredPluralAttributes()) { if (pa.getCollectionType() == PluralAttribute.CollectionType.LIST) { List<?> value = (List<?>) getValue(mtValue, mt.getAttribute(pa.getName())); if (value != null && !value.isEmpty()) { ListJoin<T, ?> join = mtPath.join(mt.getDeclaredList(pa.getName())); predicates.add(join.in(value)); } } if (pa.getCollectionType() == PluralAttribute.CollectionType.SET) { Set<?> value = (Set<?>) getValue(mtValue, mt.getAttribute(pa.getName())); if (value != null && !value.isEmpty()) { SetJoin<T, ?> join = mtPath.join(mt.getDeclaredSet(pa.getName())); predicates.add(join.in(value)); } } } return predicates; } /** * Invoke byExample method for each not null x-to-one association * when their pk is not set. This allows you * to search entities based on an associated entity's properties * value. */ @SuppressWarnings("unchecked") public <T extends Persistable, M2O extends Persistable> List<Predicate> byExampleOnXToOne( final ManagedType<T> mt, final Root<T> mtPath, final T mtValue, final SearchParameters sp, final CriteriaBuilder builder) { List<Predicate> predicates = new ArrayList<Predicate>(); for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) { if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { // M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName())); if (m2oValue != null) { Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType(); ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType); Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr); predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder)); } } } return predicates; } private <T> Object getValue(final T example, final Attribute<? super T, ?> attr) { Object value = null; try { if (attr.getJavaMember() instanceof Method) { value = ((Method) attr.getJavaMember()).invoke(example, new Object[0]); } else if (attr.getJavaMember() instanceof Field) { value = ReflectionUtils.getField((Field) attr.getJavaMember(), example); } if (value instanceof ValueHolderInterface) { value = ((ValueHolderInterface) value).getValue(); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } return value; } }; }
From source file:org.easy.criteria.CriteriaComposer.java
/** * Creates a singular join with the next entity. * /*from w w w . jav a 2s .c o m*/ * @param <R> * - The entity type to join with. (right side) * @param attribute * - SingularAttribute of this entity that has reference to next * entity * @return - Sub criteria for the next entity */ @SuppressWarnings("unchecked") public <V> CriteriaComposer<V> join(JoinType joinType, SingularAttribute<? super E, V> attribute, CriteriaComposer<V> subCriteria) { Preconditions.checkNotNull(attribute); Class<V> classToJoin = attribute.getBindableJavaType(); JoinContainer<E> join = new JoinContainer<E>(joinType, attribute); // Don't overwrite join if (_joins.containsKey(join)) return (CriteriaComposer<V>) _joins.get(join); if (subCriteria == null) subCriteria = new CriteriaComposer<V>(classToJoin); _joins.put(join, subCriteria); log.debug("Addeding join " + joinType.toString() + " on " + classToJoin.getSimpleName() + " " + attribute.getName()); return subCriteria; }
From source file:org.kuali.rice.krad.data.jpa.eclipselink.EclipseLinkJpaMetadataProviderImpl.java
/** * {@inheritDoc}/*from w w w .j a v a2 s .c o m*/ */ @Override protected void populateImplementationSpecificRelationshipLevelMetadata(DataObjectRelationshipImpl relationship, SingularAttribute<?, ?> rd) { // We need to go into the repository and grab the table name. Class<?> referencedClass = rd.getBindableJavaType(); EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass); if (referencedEntityType instanceof EntityTypeImpl) { relationship.setBackingObjectName( ((EntityTypeImpl<?>) referencedEntityType).getDescriptor().getTableName()); } // Set to read only if store (save) operations should not be pushed through PersistentAttributeType persistentAttributeType = rd.getPersistentAttributeType(); if (rd instanceof SingularAttributeImpl) { SingularAttributeImpl<?, ?> rel = (SingularAttributeImpl<?, ?>) rd; OneToOneMapping relationshipMapping = (OneToOneMapping) rel.getMapping(); relationship.setReadOnly(relationshipMapping.isReadOnly()); relationship.setSavedWithParent(relationshipMapping.isCascadePersist()); relationship.setDeletedWithParent(relationshipMapping.isCascadeRemove()); relationship.setLoadedAtParentLoadTime( relationshipMapping.isCascadeRefresh() && !relationshipMapping.isLazy()); relationship.setLoadedDynamicallyUponUse( relationshipMapping.isCascadeRefresh() && relationshipMapping.isLazy()); List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>(); for (DatabaseField parentField : relationshipMapping.getForeignKeyFields()) { String parentFieldName = getPropertyNameFromDatabaseColumnName(rd.getDeclaringType(), parentField.getName()); if (parentFieldName != null) { DatabaseField childField = relationshipMapping.getSourceToTargetKeyFields().get(parentField); if (childField != null) { // the target field is always done by column name. So, we need to get into the target entity and // find the associated field :-( // If the lookup fails, we will at least have the column name String childFieldName = getPropertyNameFromDatabaseColumnName(referencedEntityType, childField.getName()); if (childFieldName != null) { attributeRelationships .add(new DataObjectAttributeRelationshipImpl(parentFieldName, childFieldName)); } } else { LOG.warn("Unable to find child field reference. There may be a JPA mapping problem on " + rd.getDeclaringType().getJavaType() + ": " + relationship); } } } relationship.setAttributeRelationships(attributeRelationships); populateInverseRelationship(relationshipMapping, relationship); } else { // get what we can based on JPA values (note that we just set some to have values here) relationship.setReadOnly(persistentAttributeType == PersistentAttributeType.MANY_TO_ONE); relationship.setSavedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE); relationship.setDeletedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE); relationship.setLoadedAtParentLoadTime(true); relationship.setLoadedDynamicallyUponUse(false); } }
From source file:org.querybyexample.jpa.ByExampleUtil.java
/** * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated * entity's properties value.//from w ww . j a va2 s . co m */ @SuppressWarnings("unchecked") public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne( ManagedType<T> mt, Root<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) { List<Predicate> predicates = newArrayList(); for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) { if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { M2O m2oValue = (M2O) JpaUtil.getValue(mtValue, mt.getAttribute(attr.getName())); Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType(); Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr); ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType); if (m2oValue != null) { if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId())); } else { predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder)); } } } } return predicates; }