Example usage for javax.persistence.metamodel EntityType getIdType

List of usage examples for javax.persistence.metamodel EntityType getIdType

Introduction

In this page you can find the example usage for javax.persistence.metamodel EntityType getIdType.

Prototype

Type<?> getIdType();

Source Link

Document

Return the type that represents the type of the id.

Usage

From source file:org.lightadmin.core.config.bootstrap.LightAdminBeanDefinitionRegistryPostProcessor.java

private Class createDynamicRepositoryClass(Class domainType, EntityManager entityManager) {
    EntityType entityType = entityManager.getMetamodel().entity(domainType);
    Class idType = entityType.getIdType().getJavaType();

    return classFactory.createDynamicRepositoryClass(domainType, idType);
}

From source file:org.apache.click.extras.jpa.JpaForm.java

/**
 * Create a new JpaForm with the given form name and value object
 * class.//from ww w. j  ava 2  s. com
 *
 * @param name the form name
 * @param valueClass the value object class
 */
public JpaForm(String name, Class valueClass) {
    super(name);

    if (valueClass == null) {
        throw new IllegalArgumentException("Null valueClass parameter");
    }

    classField = new HiddenField(FO_CLASS, String.class);
    classField.setValue(valueClass.getName());
    add(classField);

    /*
    String classname = getClassname(valueClass);
            
    ClassMetadata classMetadata =
    ((HibernateEntityManagerFactory)getEntityManagerFactory()).getSessionFactory().getClassMetadata(classname);
            
    Type identifierType = classMetadata.getIdentifierType();
    oidField = new HiddenField(FO_ID, identifierType.getReturnedClass());
    add(oidField);
     */

    Metamodel classMetadata = getEntityManager().getMetamodel();
    EntityType entityType = classMetadata.entity(valueClass);
    //Whether the identifiable type has a single id attribute.
    if (entityType.hasSingleIdAttribute()) {
        oidField = new HiddenField(FO_ID, entityType.getIdType().getJavaType());
    } else {
        throw new IllegalArgumentException("The identifiable type is idclass attribute, the form won't work!");
    }
    add(oidField);

}

From source file:org.gvnix.web.datatables.util.DatatablesUtils.java

/**
 * Execute a select query on entityClass using <a
 * href="http://www.querydsl.com/">Querydsl</a> which enables the
 * construction of type-safe SQL-like queries.
 * // ww w  .jav  a2 s  .  c o m
 * @param entity builder for entity to use in search. Represents the entity
 *        and gives access to its properties for query purposes
 * @param filterByAssociations (optional) for each related entity to join
 *        contain as key the name of the association and as value the List
 *        of related entity fields to filter by
 * @param orderByAssociations (optional) for each related entity to order
 *        contain as key the name of the association and as value the List
 *        of related entity fields to order by
 * @param entityManager {@code entityClass} {@link EntityManager}
 * @param datatablesCriterias datatables parameters for query
 * @param basePredicate (optional) base filter conditions
 * @param distinct use distinct query
 * @param conversionService required by filter-by-expression and rows-on-top
 *        (otherwise optional)
 * @param messageSource required by filter-by-expression (otherwise
 *        optional)
 * @param rowsOnTopIds (optional) array with id of rows to show on top of
 *        result list
 * @return
 * @throws IllegalArgumentException
 */
public static <T, E extends Comparable<?>> SearchResults<T> findByCriteria(PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations, Map<String, List<String>> orderByAssociations,
        EntityManager entityManager, DatatablesCriterias datatablesCriterias, BooleanBuilder basePredicate,
        boolean distinct, ConversionService conversionService, MessageSource messageSource,
        Object[] rowsOnTopIds) throws IllegalArgumentException {
    // Check arguments aren't null
    Assert.notNull(entityManager);
    Assert.notNull(datatablesCriterias);

    // If null, create empty Map to avoid control code overload
    if (CollectionUtils.isEmpty(filterByAssociations)) {
        filterByAssociations = new HashMap<String, List<String>>();
    }
    if (CollectionUtils.isEmpty(orderByAssociations)) {
        orderByAssociations = new HashMap<String, List<String>>();
    }

    // true if data results must be paginated
    boolean isPaged = datatablesCriterias.getDisplaySize() != null && datatablesCriterias.getDisplaySize() > 0;

    // true if the search must take in account all columns
    boolean findInAllColumns = StringUtils.isNotEmpty(datatablesCriterias.getSearch())
            && datatablesCriterias.hasOneFilterableColumn();

    LOGGER.debug("findByCriteria for entity '{}' (paged={} findInAllColumns={})", entity.getType(), isPaged,
            findInAllColumns);

    // ----- Create queries -----

    // query will take in account datatables search, order and paging
    // criterias
    JPAQuery query = new JPAQuery(entityManager);
    query = query.from(entity);

    // baseQuery will use base search values only in order to count
    // all for success paging
    JPAQuery baseQuery = new JPAQuery(entityManager);
    baseQuery = baseQuery.from(entity);

    // ----- Entity associations for Query JOINs, ORDER BY, ... -----

    Map<String, PathBuilder<?>> associationMap = new HashMap<String, PathBuilder<?>>();

    query = prepareQueryAssociationMap(entity, filterByAssociations, datatablesCriterias, findInAllColumns,
            query, associationMap);

    // ----- Query WHERE clauses -----

    // Filters by column. Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder filtersByColumnPredicate = new BooleanBuilder();

    // Filters by table (for all columns)
    BooleanBuilder filtersByTablePredicate = new BooleanBuilder();

    try {

        // Build the filters by column expression
        if (datatablesCriterias.hasOneFilteredColumn()) {

            filtersByColumnPredicate = prepareQueryFilterPart(entity, filterByAssociations, datatablesCriterias,
                    associationMap, filtersByColumnPredicate, conversionService, messageSource);
        }

        // Build the query to search the given value in all columns
        filtersByTablePredicate = prepareQuerySearchPart(entity, filterByAssociations, datatablesCriterias,
                findInAllColumns, associationMap, filtersByTablePredicate, conversionService);
    } catch (Exception e) {
        LOGGER.error("Exception preparing filter for entity {}", entity.getType(), e);
        SearchResults<T> searchResults = new SearchResults<T>(new ArrayList<T>(0), 0, isPaged,
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplayStart(), 0)),
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplaySize(), 0)),
                0);
        return searchResults;
    }

    // ----- Query ORDER BY -----

    List<OrderSpecifier<?>> orderSpecifiersList = prepareQueryOrder(entity, orderByAssociations,
            datatablesCriterias, associationMap);

    // ----- Query results paging -----

    Long offset = null;
    Long limit = null;

    if (isPaged) {
        limit = new Long(datatablesCriterias.getDisplaySize());
    }
    if (datatablesCriterias.getDisplayStart() != null && datatablesCriterias.getDisplayStart() >= 0) {
        offset = new Long(datatablesCriterias.getDisplayStart());
    }

    // ------- manage Rows-on-top ----

    List<T> firstRows = null;

    // Decrease limits if firstRowsIds is used
    if (rowsOnTopIds != null) {
        LOGGER.trace("Prepare rows on top: {}", rowsOnTopIds);

        // Coherce row-on-top ids types
        Object[] cohercedRowsOnTopId = new Object[rowsOnTopIds.length];

        EntityType<? extends T> entityMetamodel = entityManager.getMetamodel().entity(entity.getType());
        // We always have just one id. This id can be an Embedded Id
        Class<?> idType = entityMetamodel.getIdType().getJavaType();
        @SuppressWarnings("unchecked")
        SingularAttribute<? extends T, ?> idAttr = (SingularAttribute<? extends T, ?>) entityMetamodel
                .getId(idType);

        Object curId;
        for (int i = 0; i < rowsOnTopIds.length; i++) {
            curId = rowsOnTopIds[i];
            if (curId.getClass() != idType) {
                cohercedRowsOnTopId[i] = conversionService.convert(curId, idType);
            } else {
                cohercedRowsOnTopId[i] = curId;
            }
        }

        // Create expression for rows-on-top
        BooleanExpression firstRowsInExpression = QuerydslUtils.createCollectionExpression(entity,
                idAttr.getName(), Arrays.asList(cohercedRowsOnTopId));

        LOGGER.trace("Expression for rowsOnTop: {}", firstRowsInExpression);

        // Exclude firstRows from base query
        basePredicate = basePredicate.and(firstRowsInExpression.not());

        LOGGER.trace("basePredicate to exclude rowsOnTop now is: {}", basePredicate);

        // Gets rows on top
        JPAQuery firstRowsQuery = new JPAQuery(entityManager);
        firstRowsQuery = firstRowsQuery.from(entity).where(firstRowsInExpression);

        LOGGER.trace("rowsOnTop query is: {}", firstRowsQuery);

        try {
            // TODO handle fieldSelector
            firstRows = firstRowsQuery.list(entity);
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting SQL for firstRow (sql = '{}' )", firstRowsQuery);
            throw exSql;
        }

        LOGGER.trace("Found {} rows for rowsOnTop", firstRows.size());
        // Adjust limit with rows-on-top found
        if (limit != null) {
            LOGGER.trace("Update main query limit: {} --> {}", limit, limit - firstRows.size());
            limit = limit - firstRows.size();
        }

    }

    // ----- Execute the query -----
    List<T> elements = null;

    // Compose the final query and update query var to be used to count
    // total amount of rows if needed

    if (distinct) {
        LOGGER.trace("Use distinct query!!!");
        query = query.distinct();
    }

    // Predicate for base query
    boolean hasBasePredicate = true;
    if (basePredicate == null) {
        basePredicate = new BooleanBuilder();
        hasBasePredicate = false;
    }

    // query projection to count all entities without paging
    baseQuery.where(basePredicate);

    // query projection to be used to get the results and to count filtered
    // results
    query = query.where(
            basePredicate.and(filtersByColumnPredicate.getValue()).and(filtersByTablePredicate.getValue()));

    // Calculate the total amount of rows taking in account datatables
    // search and paging criterias. When results are paginated we
    // must execute a count query, otherwise the size of matched rows List
    // is the total amount of rows
    long totalResultCount = 0;
    if (isPaged) {
        try {
            totalResultCount = query.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", query);
            throw exSql;
        }
    }

    if (offset == null) {
        offset = new Long(0);
    } else if (offset > totalResultCount) {
        // If offset value is bigger than total results,
        // offset needs start on 0
        offset = new Long(0);
    }

    // QueryModifiers combines limit and offset
    QueryModifiers queryModifiers = new QueryModifiers(limit, offset);
    LOGGER.trace("Set limit={} offset={}", limit, offset);

    // List ordered and paginated results. An empty list is returned for no
    // results.
    query = query.orderBy(orderSpecifiersList.toArray(new OrderSpecifier[orderSpecifiersList.size()]));

    LOGGER.debug("Execute query: {}", query);
    try {
        elements = query.restrict(queryModifiers).list(entity);
    } catch (PersistenceException exSql) {
        // Log query
        LOGGER.error("Error excecuting SQL: {}", query);
        throw exSql;
    }

    if (!isPaged) {
        totalResultCount = elements.size();
    }

    long totalBaseCount = totalResultCount;
    if (hasBasePredicate) {
        // Calculate the total amount of entities including base filters
        // only
        LOGGER.trace("Execute count query: {}", baseQuery);
        try {
            totalBaseCount = baseQuery.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", baseQuery);
            throw exSql;
        }
        LOGGER.trace("Found : {}", totalBaseCount);
    }

    if (firstRows != null) {
        // Adjust result with rows-on-top
        totalResultCount = totalResultCount + firstRows.size();
        totalBaseCount = totalBaseCount + firstRows.size();
        elements.addAll(0, firstRows);
    }

    // Create a new SearchResults instance
    if (limit == null) {
        limit = totalBaseCount;
    }
    SearchResults<T> searchResults = new SearchResults<T>(elements, totalResultCount, isPaged, offset, limit,
            totalBaseCount);

    LOGGER.debug("findByCriteria: return {} rows from {} (offset={} limit={})", totalResultCount,
            totalBaseCount, offset, limit);
    return searchResults;
}

From source file:org.gvnix.web.datatables.util.impl.DatatablesUtilsBeanImpl.java

/**
 * {@inheritDoc}/* w ww.  j  av a 2s  .  c om*/
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations, Map<String, List<String>> orderByAssociations,
        DatatablesCriterias datatablesCriterias, BooleanBuilder basePredicate, boolean distinct,
        Object[] rowsOnTopIds) throws IllegalArgumentException {
    // Check arguments aren't null
    EntityManager entityManager = entityManagerProvider.getEntityManager(entity.getType());
    Assert.notNull(entityManager);
    Assert.notNull(datatablesCriterias);

    // If null, create empty Map to avoid control code overload
    if (CollectionUtils.isEmpty(filterByAssociations)) {
        filterByAssociations = new HashMap<String, List<String>>();
    }
    if (CollectionUtils.isEmpty(orderByAssociations)) {
        orderByAssociations = new HashMap<String, List<String>>();
    }

    // true if data results must be paginated
    boolean isPaged = datatablesCriterias.getDisplaySize() != null && datatablesCriterias.getDisplaySize() > 0;

    // true if the search must take in account all columns
    boolean findInAllColumns = StringUtils.isNotEmpty(datatablesCriterias.getSearch())
            && datatablesCriterias.hasOneFilterableColumn();

    LOGGER.debug("findByCriteria for entity '{}' (paged={} findInAllColumns={})", entity.getType(), isPaged,
            findInAllColumns);

    // ----- Create queries -----

    // query will take in account datatables search, order and paging
    // criterias
    JPAQuery query = newJPAQuery(entityManager);
    query = query.from(entity);

    // baseQuery will use base search values only in order to count
    // all for success paging
    JPAQuery baseQuery = newJPAQuery(entityManager);
    baseQuery = baseQuery.from(entity);

    // ----- Entity associations for Query JOINs, ORDER BY, ... -----

    Map<String, PathBuilder<?>> associationMap = new HashMap<String, PathBuilder<?>>();

    query = prepareQueryAssociationMap(entity, filterByAssociations, datatablesCriterias, findInAllColumns,
            query, associationMap);

    // ----- Query WHERE clauses -----

    // Filters by column. Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder filtersByColumnPredicate = new BooleanBuilder();

    // Filters by table (for all columns)
    BooleanBuilder filtersByTablePredicate = new BooleanBuilder();

    try {

        // Build the filters by column expression
        if (datatablesCriterias.hasOneFilteredColumn()) {

            filtersByColumnPredicate = prepareQueryFilterPart(entity, filterByAssociations, datatablesCriterias,
                    associationMap, filtersByColumnPredicate);
        }

        // Build the query to search the given value in all columns
        filtersByTablePredicate = prepareQuerySearchPart(entity, filterByAssociations, datatablesCriterias,
                findInAllColumns, associationMap, filtersByTablePredicate);
    } catch (Exception e) {
        LOGGER.error("Exception preparing filter for entity {}", entity.getType(), e);
        SearchResults<T> searchResults = new SearchResults<T>(new ArrayList<T>(0), 0, isPaged,
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplayStart(), 0)),
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplaySize(), 0)),
                0);
        return searchResults;
    }

    // ----- Query ORDER BY -----

    List<OrderSpecifier<?>> orderSpecifiersList = prepareQueryOrder(entity, orderByAssociations,
            datatablesCriterias, associationMap);

    // ----- Query results paging -----

    Long offset = null;
    Long limit = null;

    if (isPaged) {
        limit = new Long(datatablesCriterias.getDisplaySize());
    }
    if (datatablesCriterias.getDisplayStart() != null && datatablesCriterias.getDisplayStart() >= 0) {
        offset = new Long(datatablesCriterias.getDisplayStart());
    }

    // ------- manage Rows-on-top ----

    List<T> firstRows = null;

    // Decrease limits if firstRowsIds is used
    if (rowsOnTopIds != null) {
        LOGGER.trace("Prepare rows on top: {}", rowsOnTopIds);

        // Coherce row-on-top ids types
        Object[] cohercedRowsOnTopId = new Object[rowsOnTopIds.length];

        EntityType<? extends T> entityMetamodel = entityManager.getMetamodel().entity(entity.getType());
        // We always have just one id. This id can be an Embedded Id
        Class<?> idType = entityMetamodel.getIdType().getJavaType();
        @SuppressWarnings("unchecked")
        SingularAttribute<? extends T, ?> idAttr = (SingularAttribute<? extends T, ?>) entityMetamodel
                .getId(idType);

        Object curId;
        for (int i = 0; i < rowsOnTopIds.length; i++) {
            curId = rowsOnTopIds[i];
            if (curId.getClass() != idType) {
                cohercedRowsOnTopId[i] = conversionService.convert(curId, idType);
            } else {
                cohercedRowsOnTopId[i] = curId;
            }
        }

        // Create expression for rows-on-top
        BooleanExpression firstRowsInExpression = querydslUtilsBean.createCollectionExpression(entity,
                idAttr.getName(), Arrays.asList(cohercedRowsOnTopId));

        LOGGER.trace("Expression for rowsOnTop: {}", firstRowsInExpression);

        // Exclude firstRows from base query
        basePredicate = basePredicate.and(firstRowsInExpression.not());

        LOGGER.trace("basePredicate to exclude rowsOnTop now is: {}", basePredicate);

        // Gets rows on top
        JPAQuery firstRowsQuery = newJPAQuery(entityManager);
        firstRowsQuery = firstRowsQuery.from(entity).where(firstRowsInExpression);

        LOGGER.trace("rowsOnTop query is: {}", firstRowsQuery);

        try {
            // TODO handle fieldSelector
            firstRows = firstRowsQuery.list(entity);
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting SQL for firstRow (sql = '{}' )", firstRowsQuery);
            throw exSql;
        }

        LOGGER.trace("Found {} rows for rowsOnTop", firstRows.size());
        // Adjust limit with rows-on-top found
        if (limit != null) {
            LOGGER.trace("Update main query limit: {} --> {}", limit, limit - firstRows.size());
            limit = limit - firstRows.size();
        }

    }

    // ----- Execute the query -----
    List<T> elements = null;

    // Compose the final query and update query var to be used to count
    // total amount of rows if needed

    if (distinct) {
        LOGGER.trace("Use distinct query!!!");
        query = query.distinct();
    }

    // Predicate for base query
    boolean hasBasePredicate = true;
    if (basePredicate == null) {
        basePredicate = new BooleanBuilder();
        hasBasePredicate = false;
    }

    // query projection to count all entities without paging
    baseQuery.where(basePredicate);

    // query projection to be used to get the results and to count filtered
    // results
    query = query.where(
            basePredicate.and(filtersByColumnPredicate.getValue()).and(filtersByTablePredicate.getValue()));

    // Calculate the total amount of rows taking in account datatables
    // search and paging criterias. When results are paginated we
    // must execute a count query, otherwise the size of matched rows List
    // is the total amount of rows
    long totalResultCount = 0;
    if (isPaged) {
        try {
            totalResultCount = query.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", query);
            throw exSql;
        }
    }

    if (offset == null) {
        offset = new Long(0);
    } else if (offset > totalResultCount) {
        // If offset value is bigger than total results,
        // offset needs start on 0
        offset = new Long(0);
    }

    // QueryModifiers combines limit and offset
    QueryModifiers queryModifiers = new QueryModifiers(limit, offset);
    LOGGER.trace("Set limit={} offset={}", limit, offset);

    // List ordered and paginated results. An empty list is returned for no
    // results.
    query = query.orderBy(orderSpecifiersList.toArray(new OrderSpecifier[orderSpecifiersList.size()]));

    LOGGER.debug("Execute query: {}", query);
    try {
        elements = query.restrict(queryModifiers).list(entity);
    } catch (PersistenceException exSql) {
        // Log query
        LOGGER.error("Error excecuting SQL: {}", query);
        throw exSql;
    }

    if (!isPaged) {
        totalResultCount = elements.size();
    }

    long totalBaseCount = totalResultCount;
    if (hasBasePredicate) {
        // Calculate the total amount of entities including base filters
        // only
        LOGGER.trace("Execute count query: {}", baseQuery);
        try {
            totalBaseCount = baseQuery.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", baseQuery);
            throw exSql;
        }
        LOGGER.trace("Found : {}", totalBaseCount);
    }

    if (firstRows != null) {
        // Adjust result with rows-on-top
        totalResultCount = totalResultCount + firstRows.size();
        totalBaseCount = totalBaseCount + firstRows.size();
        elements.addAll(0, firstRows);
    }

    // Create a new SearchResults instance
    if (limit == null) {
        limit = totalBaseCount;
    }
    SearchResults<T> searchResults = new SearchResults<T>(elements, totalResultCount, isPaged, offset, limit,
            totalBaseCount);

    LOGGER.debug("findByCriteria: return {} rows from {} (offset={} limit={})", totalResultCount,
            totalBaseCount, offset, limit);
    return searchResults;
}

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//from   w  w  w  .j  a  v a 2 s . co  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;
}