javax.persistence.metamodel.Attribute Java Examples

The following examples show how to use javax.persistence.metamodel.Attribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomSpecifications.java    From spring-boot-rest-api-helpers with MIT License 6 votes vote down vote up
public Predicate searchInAllAttributesPredicate(CriteriaBuilder builder, Root root, String text, List<String> includeOnlyFields) {

        if (!text.contains("%")) {
            text = "%" + text + "%";
        }
        final String finalText = text;

        Set<Attribute> attributes = root.getModel().getAttributes();
        List<Predicate> orPredicates = new ArrayList<>();
        for (Attribute a : attributes) {
            boolean javaTypeIsString = a.getJavaType().getSimpleName().equalsIgnoreCase("string");
            boolean shouldSearch = includeOnlyFields.isEmpty() || includeOnlyFields.contains(a.getName());
            if (javaTypeIsString && shouldSearch) {
                Predicate orPred = builder.like(root.get(a.getName()), finalText);
                orPredicates.add(orPred);
            }

        }

        return builder.or(orPredicates.toArray(new Predicate[orPredicates.size()]));

    }
 
Example #2
Source File: MetamodelAttribute.java    From spring-data-jpa-entity-graph with MIT License 6 votes vote down vote up
public static Optional<MetamodelAttribute> parse(
    Elements elements, Types types, Element element) {
  if (!(element instanceof VariableElement)) {
    return Optional.empty();
  }

  VariableElement variableElement = (VariableElement) element;
  if (variableElement.getKind() != FIELD) {
    return Optional.empty();
  }

  TypeElement attributeTypeElement = elements.getTypeElement(Attribute.class.getCanonicalName());
  if (!types.isSubtype(
      types.erasure(variableElement.asType()), types.erasure(attributeTypeElement.asType()))) {
    return Optional.empty();
  }

  return Optional.of(new MetamodelAttribute(variableElement));
}
 
Example #3
Source File: AbstractPathImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public <Y> Path<Y> get(String attributeName) {
	if ( ! canBeDereferenced() ) {
		throw illegalDereference();
	}

	final Attribute attribute = locateAttribute( attributeName );

	if ( attribute.isCollection() ) {
		final PluralAttribute<X,Y,?> pluralAttribute = (PluralAttribute<X,Y,?>) attribute;
		if ( PluralAttribute.CollectionType.MAP.equals( pluralAttribute.getCollectionType() ) ) {
			return (PluralAttributePath<Y>) this.<Object,Object,Map<Object, Object>>get( (MapAttribute) pluralAttribute );
		}
		else {
			return (PluralAttributePath<Y>) this.get( (PluralAttribute) pluralAttribute );
		}
	}
	else {
		return get( (SingularAttribute<X,Y>) attribute );
	}
}
 
Example #4
Source File: JPAQueryBuilder.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * Verify via {@link EntityManager} if one of the attributes of the selected entity
 * contains a embedded attribute.
 * Return true if at least one embedded attribute is found or false if non embedded
 * attribute is found.
 *
 * @param em according entity manager
 * @param jpqlQuery query to verify
 * @return true if at least one embedded attribute is found or false if non embedded
 * attribute is found.
 */
private static boolean containsEmbeddedAttributes(EntityManager em, String jpqlQuery) {
  Set<EntityType<?>> types = em.getMetamodel().getEntities();
  int pos = jpqlQuery.indexOf("FROM ") + 5;
  int lastpos = jpqlQuery.indexOf(" ", pos);
  final String queriedEntity = jpqlQuery.substring(pos, lastpos);
  for (EntityType<?> type : types) {
    if(queriedEntity.equals(type.getName())) {
      Set<Attribute<?, ?>> attributes = (Set<Attribute<?, ?>>) type.getAttributes();
      for (Attribute<?, ?> attribute : attributes) {
        if(jpqlQuery.contains(attribute.getName()) &&
          attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #5
Source File: BuilderUtil.java    From database-rider with Apache License 2.0 6 votes vote down vote up
public static String getColumnNameFromMetaModel(Attribute column) {
    String columnName = null;
    try {
        if (isEclipseLinkOnClasspath()) {
            columnName = ((AttributeImpl) column).getMapping().getField().getName();
        } else if (isHibernateOnClasspath() && isEntityManagerActive()) {
            AbstractEntityPersister entityMetadata = (AbstractEntityPersister) em().getEntityManagerFactory().unwrap(SessionFactory.class).getClassMetadata(column.getJavaMember().getDeclaringClass());
            columnName = entityMetadata.getPropertyColumnNames(column.getName())[0];
        }
    } catch (Exception e) {
        LOGGER.error("Could not extract database column name from column {} and type {}", column.getName(), column.getDeclaringType().getJavaType().getName(), e);
    }
    if (columnName == null) {
        columnName = convertCase(column.getName(), config);
    }
    return columnName;
}
 
Example #6
Source File: CustomSpecifications.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
private Predicate createGtPredicate(CriteriaBuilder builder, Root root, Attribute a, Object val) {
    if (val instanceof String) {
        return builder.greaterThan(builder.lower(root.get(a.getName())), ((String) val).toLowerCase());
    } else if (val instanceof Integer) {
        return builder.greaterThan(root.get(a.getName()), (Integer) val);
    }
    throw new IllegalArgumentException("val type not supported yet");
}
 
Example #7
Source File: AbstractManagedType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public Set<Attribute<? super X, ?>> getAttributes() {
	HashSet attributes = new HashSet<Attribute<X, ?>>( declaredAttributes.values() );
	if ( getSupertype() != null ) {
		attributes.addAll( getSupertype().getAttributes() );
	}
	return attributes;
}
 
Example #8
Source File: JPATypeConverter.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private static boolean isBlob(final Attribute<?, ?> currentAttribute) {
  if (currentAttribute != null) {
    AnnotatedElement annotatedElement = (AnnotatedElement) currentAttribute.getJavaMember();
    if (annotatedElement != null && annotatedElement.getAnnotation(Lob.class) != null) {
      return true;
    }
  }
  return false;
}
 
Example #9
Source File: RSQLVisitorBase.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
@SneakyThrows
protected Class getElementCollectionGenericType(Class type, Attribute attribute) {
	Member member = attribute.getJavaMember();
	if (member instanceof Field) {
		Field field = (Field) member;
		Type genericType = field.getGenericType();
		if (genericType instanceof ParameterizedType) {
			ParameterizedType rawType = (ParameterizedType) genericType;
			Class elementCollectionClass = Class.forName(rawType.getActualTypeArguments()[0].getTypeName());
			log.info("Map element collection generic type [{}] to [{}]", attribute.getName(), elementCollectionClass);
			return elementCollectionClass;
		}
	}
	return type;
}
 
Example #10
Source File: AbstractManagedType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public Attribute<? super X, ?> getAttribute(String name) {
	Attribute<? super X, ?> attribute = declaredAttributes.get( name );
	if ( attribute == null && getSupertype() != null ) {
		attribute = getSupertype().getAttribute( name );
	}
	checkNotNull( "Attribute ", attribute, name );
	return attribute;
}
 
Example #11
Source File: JPAEdmAssociationEndTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAssociationEndManyToOne() throws Exception {
  InnerMock mockFirst = new InnerMock(Attribute.PersistentAttributeType.ONE_TO_MANY);
  InnerMock mockSecond = new InnerMock(Attribute.PersistentAttributeType.MANY_TO_ONE);
  JPAEdmAssociationEnd associationEnd = new JPAEdmAssociationEnd(mockFirst, mockSecond);
  associationEnd.getBuilder().build();
  assertEquals(EdmMultiplicity.MANY, associationEnd.getEdmAssociationEnd1().getMultiplicity());
  assertEquals(EdmMultiplicity.ONE, associationEnd.getEdmAssociationEnd2().getMultiplicity());
  assertEquals("SOID", associationEnd.getEdmAssociationEnd1().getType().getName());
  assertEquals(new FullQualifiedName("salesorderprocessing", "SOID"), associationEnd.getEdmAssociationEnd1()
      .getType());
  assertTrue(associationEnd.isConsistent());
}
 
Example #12
Source File: PropertySelector.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
private void verifyPath(List<Attribute<?, ?>> attributes) {
    Class<?> from = attributes.get(0).getJavaType();
    attributes.remove(0);
    for (Attribute<?, ?> attribute : attributes) {
        if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) {
            throw new IllegalStateException("Wrong path.");
        }
        from = attribute.getJavaType();
    }
}
 
Example #13
Source File: CustomSpecifications.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
private Predicate createLikePredicate(CriteriaBuilder builder, Root<T> root, Join join, Attribute a, String val) {
    if (join == null) {
        return builder.like(root.get(a.getName()), val);
    }
    else {
        return builder.like(join.get(a.getName()), val);
    }
}
 
Example #14
Source File: AttributeNodeImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public <X> AttributeNodeImpl(
		SessionFactoryImplementor sessionFactory,
		ManagedType managedType,
		Attribute<X, T> attribute) {
	this.sessionFactory = sessionFactory;
	this.managedType = managedType;
	this.attribute = attribute;
}
 
Example #15
Source File: QueryUtil.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private static boolean containsMultiRelationFetch(Set<?> fetches) {
  for (Object fetchObj : fetches) {
    Fetch<?, ?> fetch = (Fetch<?, ?>) fetchObj;

    Attribute<?, ?> attr = fetch.getAttribute();
    if (attr.isAssociation() && attr.isCollection())
      return true;

    if (containsMultiRelationFetch(fetch.getFetches()))
      return true;
  }
  return false;
}
 
Example #16
Source File: CustomSpecifications.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
private boolean isPrimitive(Attribute attribute) {
    String attributeJavaClass = attribute.getJavaType().getSimpleName().toLowerCase();
    return attributeJavaClass.startsWith("int") ||
            attributeJavaClass.startsWith("long") ||
            attributeJavaClass.equals("boolean") ||
            attributeJavaClass.equals("string") ||
            attributeJavaClass.equals("float") ||
            attributeJavaClass.equals("double");
}
 
Example #17
Source File: PluralAttributeJoinSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public PluralAttributeJoinSupport(
		CriteriaBuilderImpl criteriaBuilder,
		Class<E> javaType,
		PathSource<O> pathSource,
		Attribute<? super O,?> joinAttribute,
		JoinType joinType) {
	super( criteriaBuilder, javaType, pathSource, joinAttribute, joinType );
}
 
Example #18
Source File: CustomSpecifications.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
public Predicate handleCleanKeyCase(CriteriaBuilder builder, Root root, Join join, CriteriaQuery query, String key, Attribute a, Object val) {
    boolean isValueCollection = val instanceof Collection;
    boolean isValTextSearch = (val instanceof String) && ((String) val).contains("%");
    if (isValueCollection) {
        return handleCollection(builder, root, join, query, a, key, (Collection) val, false);
    } else if (isValTextSearch) {
        return createLikePredicate(builder, root, join, a, (String) val);
    } else if(a.isCollection() && !a.isAssociation()) {
        return createEqualityPredicate(builder, root,  addJoinIfNotExists(root, a, false, isValueCollection), a, val);
    } else {
        return createEqualityPredicate(builder, root, join, a, val);
    }
}
 
Example #19
Source File: MapKeyHelpers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Attribute locateAttributeInternal(String attributeName) {
	if ( ! canBeDereferenced() ) {
		throw new IllegalArgumentException(
				"Map key [" + getPathSource().getPathIdentifier() + "] cannot be dereferenced"
		);
	}
	throw new UnsupportedOperationException( "Not yet supported!" );
}
 
Example #20
Source File: JpaUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize a entity. 
 * @param em entity manager to use
 * @param entity entity to initialize
 * @param depth max depth on recursion
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void initialize(EntityManager em, Object entity, int depth) {
	// return on nulls, depth = 0 or already initialized objects
	if (entity == null || depth == 0) { 
		return; 
	}
	
	PersistenceUnitUtil unitUtil = em.getEntityManagerFactory().getPersistenceUnitUtil();
	EntityType entityType = em.getMetamodel().entity(entity.getClass());
	Set<Attribute>  attributes = entityType.getDeclaredAttributes();
	
	Object id = unitUtil.getIdentifier(entity);
	
	if (id != null) {
		Object attached = em.find(entity.getClass(), unitUtil.getIdentifier(entity));

		for (Attribute a : attributes) {
			if (!unitUtil.isLoaded(entity, a.getName())) {
				if (a.isCollection()) {
					intializeCollection(em, entity, attached,  a, depth);
				}
				else if(a.isAssociation()) {
					intialize(em, entity, attached, a, depth);
				}
			}
		}
	}
}
 
Example #21
Source File: CustomSpecifications.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
private Predicate createLtePredicate(CriteriaBuilder builder, Root root, Attribute a, Object val) {
    if (val instanceof String) {
        return builder.lessThanOrEqualTo(builder.lower(root.get(a.getName())), ((String) val).toLowerCase());
    } else if (val instanceof Integer) {
        return builder.lessThanOrEqualTo(root.get(a.getName()), (Integer) val);
    }
    throw new IllegalArgumentException("val type not supported yet");
}
 
Example #22
Source File: AttributeFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
protected BaseAttributeMetadata(
		Property propertyMapping,
		AbstractManagedType<X> ownerType,
		Member member,
		Attribute.PersistentAttributeType persistentAttributeType) {
	this.propertyMapping = propertyMapping;
	this.ownerType = ownerType;
	this.member = member;
	this.persistentAttributeType = persistentAttributeType;

	final Class declaredType;

	if ( member == null ) {
		// assume we have a MAP entity-mode "class"
		declaredType = propertyMapping.getType().getReturnedClass();
	}
	else if ( Field.class.isInstance( member ) ) {
		declaredType = ( (Field) member ).getType();
	}
	else if ( Method.class.isInstance( member ) ) {
		declaredType = ( (Method) member ).getReturnType();
	}
	else if ( MapMember.class.isInstance( member ) ) {
		declaredType = ( (MapMember) member ).getType();
	}
	else {
		throw new IllegalArgumentException( "Cannot determine java-type from given member [" + member + "]" );
	}
	this.javaType = accountForPrimitiveTypes( declaredType );
}
 
Example #23
Source File: JPAEdmNameBuilder.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
public static void build(final JPAEdmAssociationEndView assocaitionEndView,
    final JPAEdmEntityTypeView entityTypeView, final JPAEdmPropertyView propertyView) {

  String namespace = buildNamespace(assocaitionEndView);

  String name = entityTypeView.getEdmEntityType().getName();
  FullQualifiedName fQName = new FullQualifiedName(namespace, name);
  assocaitionEndView.getEdmAssociationEnd1().setType(fQName);

  name = null;
  String jpaEntityTypeName = null;
  Attribute<?, ?> jpaAttribute = propertyView.getJPAAttribute();
  if (jpaAttribute.isCollection()) {
    jpaEntityTypeName = ((PluralAttribute<?, ?, ?>) jpaAttribute).getElementType().getJavaType()
        .getSimpleName();
  } else {
    jpaEntityTypeName = propertyView.getJPAAttribute().getJavaType()
        .getSimpleName();
  }

  JPAEdmMappingModelAccess mappingModelAccess = assocaitionEndView
      .getJPAEdmMappingModelAccess();

  if (mappingModelAccess != null
      && mappingModelAccess.isMappingModelExists()) {
    name = mappingModelAccess.mapJPAEntityType(jpaEntityTypeName);
  }

  if (name == null) {
    name = jpaEntityTypeName;
  }

  fQName = new FullQualifiedName(namespace, name);
  assocaitionEndView.getEdmAssociationEnd2().setType(fQName);

}
 
Example #24
Source File: JPAEdmPropertyTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setValuesToSet() {
  if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.BASIC)) {
    attributeSet.add((Attribute<? super String, String>) new JPAEdmAttribute(java.lang.String.class, "SOID"));
    attributeSet.add((Attribute<? super String, String>) new JPAEdmAttribute(java.lang.String.class, "SONAME"));
  } else if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.EMBEDDED)) {
    attributeSet.add(new JPAEdmAttribute(JPAEdmEmbeddable.class, ComplexType.ComplexTypeA.clazz.getName()));
  } else if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.MANY_TO_ONE)) {
    attributeSet.add(new JPAEdmPluralAttribute());
  }
}
 
Example #25
Source File: JPAEdmAssociationEndTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAssociationEndOneToMany() throws Exception {
  InnerMock mockFirst = new InnerMock(Attribute.PersistentAttributeType.MANY_TO_ONE);
  InnerMock mockSecond = new InnerMock(Attribute.PersistentAttributeType.ONE_TO_MANY);
  JPAEdmAssociationEnd associationEnd = new JPAEdmAssociationEnd(mockFirst, mockSecond);
  associationEnd.getBuilder().build();
  assertEquals(EdmMultiplicity.ONE, associationEnd.getEdmAssociationEnd1().getMultiplicity());
  assertEquals(EdmMultiplicity.MANY, associationEnd.getEdmAssociationEnd2().getMultiplicity());
  assertEquals("SOID", associationEnd.getEdmAssociationEnd1().getType().getName());
  assertEquals(new FullQualifiedName("salesorderprocessing", "SOID"), associationEnd.getEdmAssociationEnd1()
      .getType());
  assertTrue(associationEnd.isConsistent());
}
 
Example #26
Source File: GenericRepository.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
/**
 * Count the number of E instances.
 *
 * @param entity     a sample entity whose non-null properties may be used as search hint
 * @param sp         carries additional search information
 * @param attributes the list of attributes to the property
 * @return the number of entities matching the search.
 */
@Transactional
public int findPropertyCount(E entity, SearchParameters sp, List<Attribute<?, ?>> attributes) {
    if (sp.hasNamedQuery()) {
        return byNamedQueryUtil.numberByNamedQuery(sp).intValue();
    }
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
    Root<E> root = criteriaQuery.from(type);
    Path<?> path = jpaUtil.getPath(root, attributes);

    if (sp.getDistinct()) {
        criteriaQuery = criteriaQuery.select(builder.countDistinct(path));
    } else {
        criteriaQuery = criteriaQuery.select(builder.count(path));
    }

    // predicate
    Predicate predicate = getPredicate(criteriaQuery, root, builder, entity, sp);
    if (predicate != null) {
        criteriaQuery = criteriaQuery.where(predicate);
    }

    // construct order by to fetch or joins if needed
    orderByUtil.buildJpaOrders(sp.getOrders(), root, builder, sp);

    TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);

    applyCacheHints(typedQuery, sp);
    return typedQuery.getSingleResult().intValue();
}
 
Example #27
Source File: JpaUtil.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert the passed propertyPath into a JPA path.
 * <p>
 * Note: JPA will do joins if the property is in an associated entity.
 */
@SuppressWarnings("unchecked")
public static <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        // handle case when order on already fetched attribute
        for (Fetch<E, ?> fetch : root.getFetches()) {
            if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                path = (Join<E, ?>) fetch;
                found = true;
                break;
            }
        }
        for (Join<E, ?> join : root.getJoins()) {
            if (attribute.getName().equals(join.getAttribute().getName())) {
                path = join;
                found = true;
                break;
            }
        }
        if (!found) {
            path = path.get(attribute.getName());
        }
    }
    return (Path<F>) path;
}
 
Example #28
Source File: JPAEdmPropertyTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setValuesToSet() {
  attributeSet
      .add((Attribute<? super String, String>) new JPAEdmAttribute(
          java.lang.String.class, "SOID"));
  attributeSet
      .add((Attribute<? super String, String>) new JPAEdmAttribute(
          java.lang.String.class, "SONAME"));
}
 
Example #29
Source File: JPAEdmPropertyTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public Attribute<?, ?> getJPAReferencedAttribute() {
  JPAEdmAttribute<Object, String> refAttribute =
      new JPAEdmAttribute<Object, String>(java.lang.String.class, "SOLITID");

  return refAttribute;
}
 
Example #30
Source File: SingularAttributePath.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ManagedType<X> resolveManagedType(SingularAttribute<?, X> attribute) {
	if ( Attribute.PersistentAttributeType.BASIC == attribute.getPersistentAttributeType() ) {
		return null;
	}
	else if ( Attribute.PersistentAttributeType.EMBEDDED == attribute.getPersistentAttributeType() ) {
		return (EmbeddableType<X>) attribute.getType();
	}
	else {
		return (IdentifiableType<X>) attribute.getType();
	}
}