Search in sources :

Example 16 with Attribute

use of javax.persistence.metamodel.Attribute in project invesdwin-context-persistence by subes.

the class QueryByExampleHelper method xByExample.

private Query xByExample(final EntityManager em, final String queryStart, final Class<E> genericType, final E example, final boolean and) {
    assertEntityExampleWithoutId(example);
    final StringBuilder sb = new StringBuilder(queryStart);
    sb.append(" FROM ");
    sb.append(extractEntityName(genericType));
    sb.append(" e WHERE 1 = 1");
    final Map<String, Object> params = new HashMap<String, Object>();
    final EntityType<E> et = em.getMetamodel().entity(genericType);
    final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
    boolean firstField = true;
    for (final Attribute<? super E, ?> attr : attrs) {
        final String name = attr.getName();
        final String javaName = attr.getJavaMember().getName();
        final Field f = Reflections.findField(genericType, javaName);
        Reflections.makeAccessible(f);
        final Object value = Reflections.getField(f, example);
        if (value != null) {
            params.put(name, value);
            if (and || firstField) {
                sb.append(" AND ");
            } else {
                sb.append(" OR ");
            }
            sb.append("e.");
            sb.append(name);
            sb.append(" = :");
            sb.append(name);
            firstField = false;
        }
    }
    final Query query = em.createQuery(sb.toString());
    for (final Entry<String, Object> param : params.entrySet()) {
        query.setParameter(param.getKey(), param.getValue());
    }
    return query;
}
Also used : CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) DummyQuery(de.invesdwin.context.persistence.jpa.api.query.DummyQuery) Query(javax.persistence.Query) HashMap(java.util.HashMap) Attribute(javax.persistence.metamodel.Attribute) Field(java.lang.reflect.Field)

Example 17 with Attribute

use of javax.persistence.metamodel.Attribute in project invesdwin-context-persistence by subes.

the class QueryByExampleHelper method queryByExample.

/**
 * When and=false, all criteria are combined with OR, else AND is used.
 *
 * @see <a href="http://stackoverflow.com/questions/2880209/jpa-findbyexample">Source</a>
 */
public TypedQuery<E> queryByExample(final String persistenceUnitName, final EntityManager em, final Class<E> genericType, final E example, final boolean and, final QueryConfig config) {
    assertEntityExampleWithoutId(example);
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<E> cq = cb.createQuery(genericType);
    final Root<E> r = cq.from(genericType);
    Predicate p = cb.conjunction();
    final EntityType<E> et = em.getMetamodel().entity(genericType);
    final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
    boolean firstField = true;
    for (final Attribute<? super E, ?> attr : attrs) {
        final String name = attr.getName();
        final String javaName = attr.getJavaMember().getName();
        final Field f = Reflections.findField(genericType, javaName);
        Reflections.makeAccessible(f);
        final Object value = Reflections.getField(f, example);
        if (value != null) {
            final Predicate pred = cb.equal(r.get(name), value);
            if (and || firstField) {
                p = cb.and(p, pred);
            } else {
                p = cb.or(p, pred);
            }
            firstField = false;
        }
    }
    cq.select(r).where(p);
    final TypedQuery<E> query = em.createQuery(cq);
    QueryConfig.configure(persistenceUnitName, query, config);
    return query;
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Attribute(javax.persistence.metamodel.Attribute) Predicate(javax.persistence.criteria.Predicate) Field(java.lang.reflect.Field)

Example 18 with Attribute

use of javax.persistence.metamodel.Attribute in project teiid by teiid.

the class JPAMetadataProcessor method addPrimaryKey.

private void addPrimaryKey(MetadataFactory mf, Metamodel model, EntityType<?> entity, Table entityTable) throws TranslatorException {
    // figure out the PK
    if (entity.hasSingleIdAttribute()) {
        if (entity.getIdType().getPersistenceType().equals(PersistenceType.BASIC)) {
            SingularAttribute<?, ?> pkattr = entity.getId(entity.getIdType().getJavaType());
            addColumn(mf, pkattr.getName(), TypeFacility.getDataTypeName(getJavaDataType(pkattr.getJavaType())), entityTable);
            // $NON-NLS-1$
            mf.addPrimaryKey("PK_" + entity.getName(), Arrays.asList(pkattr.getName()), entityTable);
        } else if (entity.getIdType().getPersistenceType().equals(PersistenceType.EMBEDDABLE)) {
            SingularAttribute<?, ?> pkattr = entity.getId(entity.getIdType().getJavaType());
            for (EmbeddableType<?> embeddable : model.getEmbeddables()) {
                if (embeddable.getJavaType().equals(pkattr.getJavaType())) {
                    addSingularAttributes(mf, model, embeddable, entityTable);
                    ArrayList<String> keys = new ArrayList<String>();
                    for (Attribute<?, ?> attr : embeddable.getAttributes()) {
                        if (isSimpleType(attr.getJavaType())) {
                            keys.add(attr.getName());
                        } else {
                            throw new TranslatorException(JPAPlugin.Util.gs(JPAPlugin.Event.TEIID14003, entityTable.getName()));
                        }
                    }
                    mf.addPrimaryKey("PK_" + pkattr.getName(), keys, entityTable);
                    break;
                }
            }
        }
    } else {
        // Composite PK. If the PK is specified with @IdClass then read its attributes,
        // if those attributes are not found, add them as columns then as composite PK
        ArrayList<String> keys = new ArrayList<String>();
        for (Object obj : entity.getIdClassAttributes()) {
            SingularAttribute<?, ?> attr = (SingularAttribute) obj;
            addColumn(mf, attr.getName(), TypeFacility.getDataTypeName(getJavaDataType(attr.getJavaType())), entityTable);
            keys.add(attr.getName());
        }
        mf.addPrimaryKey("PK_" + entity.getName(), keys, entityTable);
    }
}
Also used : EmbeddableType(javax.persistence.metamodel.EmbeddableType) SingularAttribute(javax.persistence.metamodel.SingularAttribute) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) ArrayList(java.util.ArrayList) TranslatorException(org.teiid.translator.TranslatorException)

Example 19 with Attribute

use of javax.persistence.metamodel.Attribute in project lynx by TFaga.

the class JPAUtils method createWhereQueryInternal.

// Temporary methods to not break the public API
private static CriteriaWhereQuery createWhereQueryInternal(CriteriaBuilder cb, Root<?> r, QueryParameters q) {
    Predicate predicate = cb.conjunction();
    Boolean containsToMany = false;
    for (QueryFilter f : q.getFilters()) {
        Predicate np = null;
        try {
            CriteriaField criteriaField = getCriteriaField(f.getField(), r);
            if (criteriaField.containsToMany()) {
                containsToMany = true;
            }
            Path entityField = criteriaField.getPath();
            if (entityField.getModel() == null || !((Attribute) entityField.getModel()).getPersistentAttributeType().equals(Attribute.PersistentAttributeType.BASIC)) {
                continue;
            }
            @SuppressWarnings("unchecked") Path<String> stringField = (Path<String>) entityField;
            @SuppressWarnings("unchecked") Path<Date> dateField = (Path<Date>) entityField;
            @SuppressWarnings("unchecked") Path<Comparable> compField = (Path<Comparable>) entityField;
            switch(f.getOperation()) {
                case EQ:
                    if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
                        np = cb.equal(entityField, f.getDateValue());
                    } else if (f.getValue() != null) {
                        np = cb.equal(entityField, getValueForPath(entityField, f.getValue()));
                    }
                    break;
                case EQIC:
                    if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
                        np = cb.equal(cb.lower(stringField), f.getValue().toLowerCase());
                    }
                    break;
                case NEQ:
                    if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
                        np = cb.notEqual(entityField, f.getDateValue());
                    } else if (f.getValue() != null) {
                        np = cb.notEqual(entityField, getValueForPath(entityField, f.getValue()));
                    }
                    break;
                case NEQIC:
                    if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
                        np = cb.notEqual(cb.lower(stringField), f.getValue().toLowerCase());
                    }
                    break;
                case LIKE:
                    if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
                        np = cb.like(stringField, f.getValue());
                    }
                    break;
                case LIKEIC:
                    if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
                        np = cb.like(cb.lower(stringField), f.getValue().toLowerCase());
                    }
                    break;
                case GT:
                    if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
                        if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
                            np = cb.greaterThan(dateField, f.getDateValue());
                        } else if (f.getValue() != null) {
                            np = cb.greaterThan(compField, (Comparable) getValueForPath(stringField, f.getValue()));
                        }
                    }
                    break;
                case GTE:
                    if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
                        if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
                            np = cb.greaterThanOrEqualTo(dateField, f.getDateValue());
                        } else if (f.getValue() != null) {
                            np = cb.greaterThanOrEqualTo(compField, (Comparable) getValueForPath(stringField, f.getValue()));
                        }
                    }
                    break;
                case LT:
                    if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
                        if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
                            np = cb.lessThan(dateField, f.getDateValue());
                        } else if (f.getValue() != null) {
                            np = cb.lessThan(compField, (Comparable) getValueForPath(stringField, f.getValue()));
                        }
                    }
                    break;
                case LTE:
                    if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
                        if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
                            np = cb.lessThanOrEqualTo(dateField, f.getDateValue());
                        } else if (f.getValue() != null) {
                            np = cb.lessThanOrEqualTo(compField, (Comparable) getValueForPath(stringField, f.getValue()));
                        }
                    }
                    break;
                case IN:
                    np = stringField.in(f.getValues().stream().filter(Objects::nonNull).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList()));
                    break;
                case INIC:
                    if (entityField.getJavaType().equals(String.class)) {
                        np = cb.lower(stringField).in(f.getValues().stream().filter(Objects::nonNull).map(String::toLowerCase).collect(Collectors.toList()));
                    }
                    break;
                case NIN:
                    np = cb.not(stringField.in(f.getValues().stream().filter(Objects::nonNull).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList())));
                    break;
                case NINIC:
                    if (entityField.getJavaType().equals(String.class)) {
                        np = cb.not(cb.lower(stringField).in(f.getValues().stream().filter(Objects::nonNull).map(String::toLowerCase).collect(Collectors.toList())));
                    }
                    break;
                case ISNULL:
                    np = cb.isNull(entityField);
                    break;
                case ISNOTNULL:
                    np = cb.isNotNull(entityField);
                    break;
            }
        } catch (IllegalArgumentException e) {
            throw new NoSuchEntityFieldException(e.getMessage(), f.getField(), r.getJavaType().getSimpleName());
        }
        if (np != null) {
            predicate = cb.and(predicate, np);
        }
    }
    return new CriteriaWhereQuery(predicate, containsToMany);
}
Also used : CriteriaFilter(com.github.tfaga.lynx.interfaces.CriteriaFilter) java.util(java.util) ZonedDateTime(java.time.ZonedDateTime) TypedQuery(javax.persistence.TypedQuery) InvalidEntityFieldException(com.github.tfaga.lynx.exceptions.InvalidEntityFieldException) NoSuchEntityFieldException(com.github.tfaga.lynx.exceptions.NoSuchEntityFieldException) EntityType(javax.persistence.metamodel.EntityType) QueryFilter(com.github.tfaga.lynx.beans.QueryFilter) CriteriaField(com.github.tfaga.lynx.beans.CriteriaField) javax.persistence.criteria(javax.persistence.criteria) Metamodel(javax.persistence.metamodel.Metamodel) QueryParameters(com.github.tfaga.lynx.beans.QueryParameters) Tuple(javax.persistence.Tuple) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) OrderDirection(com.github.tfaga.lynx.enums.OrderDirection) EntityManager(javax.persistence.EntityManager) Field(java.lang.reflect.Field) Logger(java.util.logging.Logger) CriteriaWhereQuery(com.github.tfaga.lynx.beans.CriteriaWhereQuery) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) DateTimeParseException(java.time.format.DateTimeParseException) InvalidFieldValueException(com.github.tfaga.lynx.exceptions.InvalidFieldValueException) TupleElement(javax.persistence.TupleElement) QueryFilter(com.github.tfaga.lynx.beans.QueryFilter) CriteriaWhereQuery(com.github.tfaga.lynx.beans.CriteriaWhereQuery) CriteriaField(com.github.tfaga.lynx.beans.CriteriaField) NoSuchEntityFieldException(com.github.tfaga.lynx.exceptions.NoSuchEntityFieldException)

Example 20 with Attribute

use of javax.persistence.metamodel.Attribute in project hibernate-orm by hibernate.

the class MetadataContext method wrapUp.

@SuppressWarnings({ "unchecked" })
public void wrapUp() {
    final boolean traceEnabled = LOG.isTraceEnabled();
    if (traceEnabled) {
        LOG.trace("Wrapping up metadata context...");
    }
    boolean staticMetamodelScanEnabled = JpaStaticMetaModelPopulationSetting.determineJpaMetaModelPopulationSetting(sessionFactory.getProperties()) != JpaStaticMetaModelPopulationSetting.DISABLED;
    // we need to process types from superclasses to subclasses
    for (Object mapping : orderedMappings) {
        if (PersistentClass.class.isAssignableFrom(mapping.getClass())) {
            @SuppressWarnings("unchecked") final PersistentClass safeMapping = (PersistentClass) mapping;
            if (traceEnabled) {
                LOG.trace("Starting entity [" + safeMapping.getEntityName() + ']');
            }
            try {
                final EntityTypeImpl<?> jpa2Mapping = entityTypesByPersistentClass.get(safeMapping);
                applyIdMetadata(safeMapping, jpa2Mapping);
                applyVersionAttribute(safeMapping, jpa2Mapping);
                Iterator<Property> properties = safeMapping.getDeclaredPropertyIterator();
                while (properties.hasNext()) {
                    final Property property = properties.next();
                    if (property.getValue() == safeMapping.getIdentifierMapper()) {
                        // #buildIdClassAttributes
                        continue;
                    }
                    if (safeMapping.isVersioned() && property == safeMapping.getVersion()) {
                        // skip the version property, it was already handled previously.
                        continue;
                    }
                    final Attribute attribute = attributeFactory.buildAttribute(jpa2Mapping, property);
                    if (attribute != null) {
                        jpa2Mapping.getBuilder().addAttribute(attribute);
                    }
                }
                jpa2Mapping.lock();
                if (staticMetamodelScanEnabled) {
                    populateStaticMetamodel(jpa2Mapping);
                }
            } finally {
                if (traceEnabled) {
                    LOG.trace("Completed entity [" + safeMapping.getEntityName() + ']');
                }
            }
        } else if (MappedSuperclass.class.isAssignableFrom(mapping.getClass())) {
            @SuppressWarnings("unchecked") final MappedSuperclass safeMapping = (MappedSuperclass) mapping;
            if (traceEnabled) {
                LOG.trace("Starting mapped superclass [" + safeMapping.getMappedClass().getName() + ']');
            }
            try {
                final MappedSuperclassTypeImpl<?> jpa2Mapping = mappedSuperclassByMappedSuperclassMapping.get(safeMapping);
                applyIdMetadata(safeMapping, jpa2Mapping);
                applyVersionAttribute(safeMapping, jpa2Mapping);
                Iterator<Property> properties = safeMapping.getDeclaredPropertyIterator();
                while (properties.hasNext()) {
                    final Property property = properties.next();
                    if (safeMapping.isVersioned() && property == safeMapping.getVersion()) {
                        // skip the version property, it was already handled previously.
                        continue;
                    }
                    final Attribute attribute = attributeFactory.buildAttribute(jpa2Mapping, property);
                    if (attribute != null) {
                        jpa2Mapping.getBuilder().addAttribute(attribute);
                    }
                }
                jpa2Mapping.lock();
                if (staticMetamodelScanEnabled) {
                    populateStaticMetamodel(jpa2Mapping);
                }
            } finally {
                if (traceEnabled) {
                    LOG.trace("Completed mapped superclass [" + safeMapping.getMappedClass().getName() + ']');
                }
            }
        } else {
            throw new AssertionFailure("Unexpected mapping type: " + mapping.getClass());
        }
    }
    if (staticMetamodelScanEnabled) {
        for (EmbeddableTypeImpl embeddable : embeddables.values()) {
            populateStaticMetamodel(embeddable);
        }
    }
}
Also used : AssertionFailure(org.hibernate.annotations.common.AssertionFailure) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) MappedSuperclass(org.hibernate.mapping.MappedSuperclass) Iterator(java.util.Iterator) Property(org.hibernate.mapping.Property) PersistentClass(org.hibernate.mapping.PersistentClass)

Aggregations

Attribute (javax.persistence.metamodel.Attribute)31 SingularAttribute (javax.persistence.metamodel.SingularAttribute)21 ListAttribute (javax.persistence.metamodel.ListAttribute)13 PluralAttribute (javax.persistence.metamodel.PluralAttribute)12 MapAttribute (javax.persistence.metamodel.MapAttribute)10 Metamodel (javax.persistence.metamodel.Metamodel)9 CollectionAttribute (javax.persistence.metamodel.CollectionAttribute)6 SetAttribute (javax.persistence.metamodel.SetAttribute)6 Path (javax.persistence.criteria.Path)5 EntityType (javax.persistence.metamodel.EntityType)5 ManagedType (javax.persistence.metamodel.ManagedType)5 EntityManager (javax.persistence.EntityManager)4 TypedQuery (javax.persistence.TypedQuery)4 Predicate (javax.persistence.criteria.Predicate)4 Field (java.lang.reflect.Field)3 Expression (javax.persistence.criteria.Expression)3 From (javax.persistence.criteria.From)3 Root (javax.persistence.criteria.Root)3 IdentifiableType (javax.persistence.metamodel.IdentifiableType)3 Type (javax.persistence.metamodel.Type)3