Example usage for javax.persistence.criteria Root getModel

List of usage examples for javax.persistence.criteria Root getModel

Introduction

In this page you can find the example usage for javax.persistence.criteria Root getModel.

Prototype

EntityType<X> getModel();

Source Link

Document

Return the metamodel entity corresponding to the root.

Usage

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

public <T extends Identifiable<?>> Predicate byExampleOnEntity(Root<T> rootPath, T entityValue,
        CriteriaBuilder builder, SearchParameters sp) {
    if (entityValue == null) {
        return null;
    }//from   w ww . jav  a  2s .c  om

    Class<T> type = rootPath.getModel().getBindableJavaType();
    ManagedType<T> mt = em.getMetamodel().entity(type);

    List<Predicate> predicates = newArrayList();
    predicates.addAll(byExample(mt, rootPath, entityValue, sp, builder));
    predicates.addAll(byExampleOnCompositePk(rootPath, entityValue, sp, builder));
    predicates.addAll(byExampleOnXToOne(mt, rootPath, entityValue, sp, builder)); // 1 level deep only
    predicates.addAll(byExampleOnXToMany(mt, rootPath, entityValue, sp, builder));
    return jpaUtil.concatPredicate(sp, builder, 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 .co  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:name.marcelomorales.siqisiqi.openjpa.spring.OpenJpaRepositoryFactory.java

protected Object getTargetRepository(final RepositoryMetadata metadata) {
    return new OpenJpaRepositoryImpl<>((Class<T>) metadata.getDomainType(), entityManager,
            new OrmFinderSettings<T, I>() {

                @Override/*w w  w .  java  2 s  .  c  o  m*/
                public boolean returnsNullIfTermsAreNull() {
                    final Class<?> repositoryInterface = metadata.getRepositoryInterface();
                    if (!repositoryInterface.isAnnotationPresent(OpenJpaSettings.class)) {
                        return super.returnsNullIfTermsAreNull();
                    }

                    final OpenJpaSettings annotation = repositoryInterface.getAnnotation(OpenJpaSettings.class);
                    return annotation.returnsNullIfTermsAreNull();
                }

                @Override
                public Iterable<Path<String>> getFullTexts(Root<T> from, Class<T> aClass) {
                    final Class<?> repositoryInterface = metadata.getRepositoryInterface();
                    if (!repositoryInterface.isAnnotationPresent(OpenJpaSettings.class)) {
                        return super.getFullTexts(from, aClass);
                    }

                    final OpenJpaSettings annotation = repositoryInterface.getAnnotation(OpenJpaSettings.class);
                    String[] fulltexts = annotation.fullTexts();
                    List<Path<String>> paths = new ArrayList<>(fulltexts.length);
                    for (String fulltext : fulltexts) {
                        paths.add(from.<String>get(fulltext));
                    }
                    return paths;
                }

                @Override
                public ComparisonStyle getComparisonStyle() {
                    final Class<?> repositoryInterface = metadata.getRepositoryInterface();
                    if (!repositoryInterface.isAnnotationPresent(OpenJpaSettings.class)) {
                        return new ComparisonStyle.Default();
                    }

                    final OpenJpaSettings annotation = repositoryInterface.getAnnotation(OpenJpaSettings.class);

                    final ComparisonStyle.Default aDefault = new ComparisonStyle.Default();
                    aDefault.setDisjunction(annotation.disjunction());
                    aDefault.setExcludeDefault(annotation.excludeDefault());
                    aDefault.setExcludeIdentity(annotation.excludeIdentity());
                    aDefault.setExcludeNull(annotation.excludeNull());
                    aDefault.setExcludeVersion(annotation.excludeVersion());
                    aDefault.setStringComparisonMode(annotation.stringComparisonMode());
                    return aDefault;
                }

                @Override
                public Path<I> countPath(Root<T> from, Class<T> aClass) {
                    final Class<I> idType = (Class<I>) metadata.getIdType();
                    final SingularAttribute<T, I> declaredId = from.getModel().getDeclaredId(idType);
                    return from.get(declaredId);
                }

                @Override
                public Attribute<?, ?>[] betweens(Root<T> from, Class<T> aClass) {
                    final Class<?> repositoryInterface = metadata.getRepositoryInterface();
                    if (!repositoryInterface.isAnnotationPresent(OpenJpaSettings.class)) {
                        return super.betweens(from, aClass);
                    }

                    final EntityType<T> model = from.getModel();
                    final OpenJpaSettings annotation = repositoryInterface.getAnnotation(OpenJpaSettings.class);
                    String[] betweens = annotation.betweens();
                    Attribute[] attributes = new Attribute[betweens.length];
                    for (int i = 0; i < betweens.length; i++) {
                        attributes[i] = model.getSingularAttribute(betweens[i]);
                    }
                    return attributes;
                }
            });
}

From source file:org.apache.ambari.server.api.query.JpaSortBuilder.java

/**
 * Builds the list of sort orders based on the supplied request and JPA
 * predicate visitor./*from w  ww  .  j  ava2s.  c o m*/
 *
 * @param sortRequests
 *          the Ambari sort request properties to turn into a JPA sort
 *          request. If {@code null} or the {@link SortRequestProperty} list
 *          is null, an empty list is returned.
 * @param visitor
 *          a visitor that knows how to convert the Ambari properties into
 *          {@link SingularAttribute} (not {@code null}).
 * @return a list of sorts or an empty list if none (never {@code null}).
 */
public List<Order> buildSortOrders(SortRequest sortRequest, JpaPredicateVisitor<T> visitor) {

    if (null == sortRequest || null == sortRequest.getProperties()) {
        return Collections.emptyList();
    }

    CriteriaBuilder builder = visitor.getCriteriaBuilder();
    List<SortRequestProperty> sortProperties = sortRequest.getProperties();
    List<Order> sortOrders = new ArrayList<Order>(sortProperties.size());

    for (SortRequestProperty sort : sortProperties) {
        String propertyId = sort.getPropertyId();

        List<? extends SingularAttribute<?, ?>> singularAttributes = visitor.getPredicateMapping(propertyId);

        if (null == singularAttributes || singularAttributes.size() == 0) {
            continue;
        }

        Path<?> path = null;
        for (SingularAttribute<?, ?> singularAttribute : singularAttributes) {
            if (null == path) {

                CriteriaQuery<T> query = visitor.getCriteriaQuery();
                Set<Root<?>> roots = query.getRoots();

                // if there are existing roots; use the existing roots to prevent more
                // roots from being added potentially causing a cartesian product
                // where we don't want one
                if (null != roots && !roots.isEmpty()) {
                    Iterator<Root<?>> iterator = roots.iterator();
                    while (iterator.hasNext()) {
                        Root<?> root = iterator.next();

                        Class<?> visitorEntityClass = visitor.getEntityClass();
                        if (ObjectUtils.equals(visitorEntityClass, root.getJavaType())
                                || ObjectUtils.equals(visitorEntityClass, root.getModel().getJavaType())) {
                            path = root.get(singularAttribute.getName());
                            break;
                        }
                    }
                }

                // no roots exist already which match this entity class, create a new
                // path
                if (null == path) {
                    path = query.from(visitor.getEntityClass()).get(singularAttribute.getName());
                }
            } else {
                path = path.get(singularAttribute.getName());
            }
        }

        Order sortOrder = null;
        if (sort.getOrder() == org.apache.ambari.server.controller.spi.SortRequest.Order.ASC) {
            sortOrder = builder.asc(path);
        } else {
            sortOrder = builder.desc(path);
        }

        sortOrders.add(sortOrder);
    }

    return sortOrders;
}

From source file:org.batoo.jpa.core.impl.criteria.AbstractCriteriaQueryImpl.java

/**
 * {@inheritDoc}/* ww w . j  a  va  2 s .c om*/
 * 
 */
@Override
public String generateJpql() {
    final StringBuilder builder = new StringBuilder();

    this.ensureSelection();

    builder.append("select ");

    // append distinct if necessary
    if (this.distinct) {
        builder.append("distinct ");
    }

    builder.append(this.selection.generateJpqlSelect(this, true));

    final Collection<String> roots = Collections2.transform(this.getRoots(), new Function<Root<?>, String>() {

        @Override
        public String apply(Root<?> input) {
            final RootImpl<?> root = (RootImpl<?>) input;

            final StringBuilder builder = new StringBuilder(input.getModel().getName());

            if (StringUtils.isNotBlank(input.getAlias())) {
                builder.append(" as ").append(input.getAlias());
            }

            final String joins = root.generateJpqlJoins(AbstractCriteriaQueryImpl.this);

            if (StringUtils.isNotBlank(joins)) {
                builder.append("\n").append(BatooUtils.indent(joins));
            }
            return builder.toString();
        }
    });
    builder.append("\nfrom ").append(Joiner.on(", ").join(roots));

    if (this.getRestriction() != null) {
        builder.append("\nwhere\n\t").append(this.getRestriction().generateJpqlRestriction(this));
    }

    if (this.getGroupList().size() > 0) {
        final String groupBy = Joiner.on(", ")
                .join(Lists.transform(this.getGroupList(), new Function<Expression<?>, String>() {

                    @Override
                    public String apply(Expression<?> input) {
                        return ((AbstractExpression<?>) input)
                                .generateJpqlRestriction(AbstractCriteriaQueryImpl.this);
                    }
                }));

        builder.append("\ngroup by\n\t").append(groupBy);
    }

    if (this.getGroupRestriction() != null) {
        builder.append("\nhaving\n\t").append(this.getGroupRestriction().generateJpqlRestriction(this));
    }

    return builder.toString();
}

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

public <T extends Identifiable<?>> Predicate byExampleOnEntity(Root<T> rootPath, T entityValue,
        CriteriaBuilder builder, SearchParameters sp) {
    if (entityValue == null) {
        return null;
    }/*from  ww  w.j  av  a2 s  .  c o  m*/

    Class<T> type = rootPath.getModel().getBindableJavaType();
    ManagedType<T> mt = em.getMetamodel().entity(type);

    List<Predicate> predicates = newArrayList();
    predicates.addAll(byExample(mt, rootPath, entityValue, sp, builder));
    predicates.addAll(byExampleOnCompositePk(rootPath, entityValue, sp, builder));
    predicates.addAll(byExampleOnXToOne(mt, rootPath, entityValue, sp, builder)); // 1 level deep only
    predicates.addAll(byExampleOnManyToMany(mt, rootPath, entityValue, sp, builder));
    return JpaUtil.concatPredicate(sp, builder, predicates);
}

From source file:ru.savvy.jpafilterbuilder.FilterCriteriaBuilder.java

/**
 * Resulting query with filters and orders, if orders are empty, than makes
 * default ascending ordering by root id to prevent paging confuses
 *
 * @return// w  w w .j av  a2s . c o m
 */
public CriteriaQuery<T> getQuery() {
    CriteriaQuery<T> query = cb.createQuery(clazz);
    Root<T> root = query.from(clazz);
    applyFilters(root, query);
    applyOrders(root, query);

    // add default ordering
    if (query.getOrderList() == null || query.getOrderList().isEmpty()) {
        EntityType<T> entityType = root.getModel();
        try {
            Field sortField = getSortAnnotation(entityType.getBindableJavaType());
            if (sortField == null)
                query.orderBy(
                        cb.asc(root.get(entityType.getId(entityType.getIdType().getJavaType()).getName())));
            else {
                DefaultOrder order = sortField.getAnnotation(DefaultOrder.class);
                if (order.asc()) {
                    query.orderBy(cb.asc(root.get(sortField.getName())));
                } else {
                    query.orderBy(cb.desc(root.get(sortField.getName())));
                }

            }
        } catch (Exception ex) {
            logger.warn("In" + this.getClass().getName(), ex);
        }
    }
    return query;
}