Example usage for javax.persistence.metamodel SingularAttribute getJavaType

List of usage examples for javax.persistence.metamodel SingularAttribute getJavaType

Introduction

In this page you can find the example usage for javax.persistence.metamodel SingularAttribute getJavaType.

Prototype

Class<Y> getJavaType();

Source Link

Document

Return the Java type of the represented attribute.

Usage

From source file:com.dbs.sdwt.jpa.ByExampleUtil.java

public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, T mtValue, SearchParameters sp,
        CriteriaBuilder builder) {//  w  ww . j  a v a  2  s.  com
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE //
                || attr.getPersistentAttributeType() == ONE_TO_ONE //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = jpaUtil.getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(jpaUtil.stringPredicate(mtPath.get(jpaUtil.stringAttribute(mt, attr)),
                            attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(jpaUtil.attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}

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 v a 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:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java

private Predicate[] BuildFilterPredicates(Root<ENTITY> root, String search, List<String> searchProperties) {
    if (Strings.isNullOrEmpty(search)) {
        return new Predicate[] {};
    }//from   w  w w  .jav  a 2  s  .  c o m
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    EntityType<ENTITY> type = entityManager.getMetamodel().entity(entityClass);

    String[] split = search.split(",");

    Set<SingularAttribute<? super ENTITY, ?>> attributes = type.getSingularAttributes();
    List<Predicate> predicates = new ArrayList<Predicate>(split.length * attributes.size());
    for (String searchElem : split) {
        String searchProperty = null;
        if (searchElem.contains(":")) {
            String[] propSearchs = searchElem.trim().split(":", 2);
            searchElem = propSearchs[1];
            searchProperty = propSearchs[0];
        }

        boolean numeric;
        try {
            Double.parseDouble(searchElem);
            numeric = true;
        } catch (Exception e) {
            numeric = false;
        }
        for (SingularAttribute<? super ENTITY, ?> attribute : attributes) {
            if (searchProperties != null && !searchProperties.isEmpty()
                    && !searchProperties.contains(attribute.getName())) {
                continue; // skip this property as its not listed in searchable properties
            }
            if (searchProperty != null && !searchProperty.equals(attribute.getName())) {
                continue; // skip this property as we are searching for specific property
            }
            Class<?> javaType = attribute.getJavaType();
            if (javaType == String.class) {
                @SuppressWarnings("unchecked")
                Predicate like = builder.like(
                        builder.lower(root.get((SingularAttribute<ENTITY, String>) attribute)),
                        "%" + searchElem.toLowerCase().trim() + "%");
                predicates.add(like);
            } else if (numeric && (Number.class.isAssignableFrom(javaType) || javaType == int.class
                    || javaType == short.class || javaType == long.class || javaType == float.class
                    || javaType == double.class || javaType == byte.class)) {
                Predicate like = builder.equal(root.get(attribute), searchElem.toLowerCase().trim());
                predicates.add(like);
            }
            //TODO fancy types
            // enums
            // char   
            // boolean   
        }
    }
    return predicates.toArray(new Predicate[] {});
}

From source file:org.querybyexample.jpa.ByExampleUtil.java

/**
 * Add a predicate for each simple property whose value is not null.
 */// w  w  w.  jav a 2s. co  m
public <T> List<Predicate> byExample(ManagedType<T> mt, Path<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 //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = JpaUtil.getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(JpaUtil.stringPredicate(mtPath.get(JpaUtil.stringAttribute(mt, attr)),
                            attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(JpaUtil.attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}