Example usage for javax.persistence.criteria CriteriaBuilder createQuery

List of usage examples for javax.persistence.criteria CriteriaBuilder createQuery

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder createQuery.

Prototype

<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

Source Link

Document

Create a CriteriaQuery object with the specified result type.

Usage

From source file:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public long findCount() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);
    Root<T> customer = criteriaQuery.from(entityClass);
    criteriaQuery.select(cb.count(customer));
    Query query = em.createQuery(criteriaQuery);
    return (Long) query.getSingleResult();
}

From source file:de.hopmann.repositories.cran.service.CRANPackageListingService.java

public void removeCurrentListing() {
    // TODO Bulk removal, JPQL not cascading
    // entityManager.createQuery("DELETE FROM DependencyEntity").executeUpdate();
    // or/*from  www  .  j a v a  2 s . c om*/
    // entityManager.createQuery("DELETE FROM PackageEntity").executeUpdate();

    // Alternative

    // CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    //
    // CriteriaDelete<PackageEntity> delete = cb
    // .createCriteriaDelete(PackageEntity.class);
    // Root<PackageEntity> p = delete.from(PackageEntity.class);
    // delete.where(cb.isFalse(p.get(PackageEntity_.archived)));
    //
    // entityManager.createQuery(delete).executeUpdate();

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<CRANPackageEntity> query = cb.createQuery(CRANPackageEntity.class);
    Root<CRANPackageEntity> p = query.from(CRANPackageEntity.class);
    query.where(cb.isFalse(p.get(CRANPackageEntity_.archived)));

    List<CRANPackageEntity> resultList = entityManager.createQuery(query).getResultList();

    for (CRANPackageEntity cRANPackageEntity : resultList) {
        entityManager.remove(cRANPackageEntity);
    }
}

From source file:se.inera.intyg.intygstjanst.persistence.model.dao.impl.CertificateDaoImpl.java

@Override
public List<Certificate> findCertificate(Personnummer civicRegistrationNumber, List<String> types,
        LocalDate fromDate, LocalDate toDate, List<String> careUnits) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Certificate> query = criteriaBuilder.createQuery(Certificate.class);
    Root<Certificate> root = query.from(Certificate.class);

    root.fetch("states", JoinType.LEFT);

    if (civicRegistrationNumber == null) {
        return Collections.emptyList();
    }/*from   w w w .  j a  v  a2s. com*/

    List<Predicate> predicates = new ArrayList<>();

    // meta data has to match civic registration number
    predicates.add(criteriaBuilder.equal(root.get("civicRegistrationNumber"),
            DaoUtil.formatPnrForPersistence(civicRegistrationNumber)));

    // filter by certificate types
    if (types != null && !types.isEmpty()) {
        predicates.add(criteriaBuilder.lower(root.<String>get("type")).in(toLowerCase(types)));
    }

    // filter by care unit
    if (careUnits != null && !careUnits.isEmpty()) {
        predicates.add(root.<String>get("careUnitId").in(careUnits));
    }

    query.where(predicates.toArray(new Predicate[predicates.size()]));

    // order by signed date
    query.orderBy(criteriaBuilder.asc(root.get("signedDate")));

    List<Certificate> tmpResult = entityManager.createQuery(query).getResultList();
    List<Certificate> result = filterDuplicates(tmpResult);

    // expect a small number, so lets filter in memory
    return new DateFilter(result).filter(fromDate, toDate);
}

From source file:org.osiam.resource_server.storage.dao.ResourceDao.java

public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count,
        int startIndex, String sortBy, String sortOrder, FilterParser<T> filterParser) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<T> resourceQuery = cb.createQuery(clazz);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class);
    Root<T> internalIdRoot = internalIdQuery.from(clazz);
    internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId));

    if (filterTree != null && filterTree.getChildCount() > 0) {
        Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot);
        internalIdQuery.where(predicate);
    }/*from w  w w  . ja v  a2s  .com*/

    resourceQuery.select(resourceRoot)
            .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible
    Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id);

    if (sortBy != null && !sortBy.isEmpty()) {
        sortByField = filterParser.createSortByField(sortBy, resourceRoot);
    }

    // default order is ascending
    Order order = cb.asc(sortByField);

    if (sortOrder.equalsIgnoreCase("descending")) {
        order = cb.desc(sortByField);
    }

    resourceQuery.orderBy(order);

    TypedQuery<T> query = em.createQuery(resourceQuery);
    query.setFirstResult(startIndex);
    query.setMaxResults(count);

    List<T> results = query.getResultList();

    long totalResult = getTotalResults(clazz, internalIdQuery);

    return new SearchResult<>(results, totalResult);
}

From source file:com.vladmihalcea.HibernateFetchStrategyTest.java

@Test
public void test() {

    final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() {
        @Override/*from   w w w  . ja  v a  2s.c  o m*/
        public Long doInTransaction(TransactionStatus transactionStatus) {

            Company company = new Company();
            company.setName("TV Company");
            entityManager.persist(company);

            Product product = new Product("tvCode");
            product.setName("TV");
            product.setCompany(company);

            Image frontImage = new Image();
            frontImage.setName("front image");
            frontImage.setIndex(0);

            Image sideImage = new Image();
            sideImage.setName("side image");
            sideImage.setIndex(1);

            product.addImage(frontImage);
            product.addImage(sideImage);

            WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();
            warehouseProductInfo.setQuantity(101);
            product.addWarehouse(warehouseProductInfo);

            Importer importer = new Importer();
            importer.setName("Importer");
            entityManager.persist(importer);
            product.setImporter(importer);

            entityManager.persist(product);
            return product.getId();
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            LOG.info("Fetch using find");
            Product product = entityManager.find(Product.class, productId);
            assertNotNull(product);
            return null;
        }
    });

    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            LOG.info("Fetch using JPQL");
            Product product = entityManager
                    .createQuery("select p " + "from Product p " + "where p.id = :productId", Product.class)
                    .setParameter("productId", productId).getSingleResult();
            assertNotNull(product);
            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {

            LOG.info("Fetch using Criteria");

            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> cq = cb.createQuery(Product.class);
            Root<Product> productRoot = cq.from(Product.class);
            cq.where(cb.equal(productRoot.get("id"), productId));
            Product product = entityManager.createQuery(cq).getSingleResult();
            assertNotNull(product);
            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            LOG.info("Fetch using join fetch JPQL");

            Product product = product = entityManager.createQuery("select p " + "from Product p "
                    + "inner join fetch p.warehouseProductInfo " + "inner join fetch p.importer", Product.class)
                    .getSingleResult();
            assertNotNull(product);

            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {

            Image image = entityManager
                    .createQuery("select i " + "from Image i " + "inner join fetch i.product p "
                            + "where p.id = :productId", Image.class)
                    .setParameter("productId", productId).getResultList().get(0);
            assertNotNull(image);

            return null;
        }
    });
}

From source file:utils.jpa.EntityResource.java

private List<T> getAllPriv(@BeanParam TableSearchQuery tb, List<String> fieldsSearchBy) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    cq.select(root);//from   ww w. ja  v  a2 s . co m

    //setting order
    if (tb.getOrderType().equals(OrderType.DESC)) {
        cq.orderBy(cb.desc(root.get(tb.getOrder())));
    } else {
        cq.orderBy(cb.asc(root.get(tb.getOrder())));
    }

    Query query = tb.createQuery(em, cb, cq, root);
    if (query == null) {
        query = createCommonQuery(cb, cq, root, tb, fieldsSearchBy);
    }

    if (tb.getOffset() > 0) {
        query.setFirstResult(tb.getOffset());
    }
    if (tb.getLimit() > 0) {
        query.setMaxResults(tb.getLimit());
    }

    return query.getResultList();
}

From source file:net.nan21.dnet.core.business.service.entity.AbstractEntityReadService.java

/**
 * Find an entity of the given type, using as filter criteria the specified
 * list of attribute values. The filter criteria must uniquely identify an
 * entity./*w  w  w.ja  v  a2  s .co m*/
 * 
 * @param entityClass
 * @param params
 * @return
 * @throws BusinessException
 */
public <T> T findEntityByAttributes(Class<T> entityClass, Map<String, Object> params) {
    CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);
    cq.select(root);
    Assert.notNull(params);
    Predicate p = null;
    if (entityClass.isAssignableFrom(IModelWithClientId.class)) {
        p = cb.equal(root.get("clientId"), Session.user.get().getClient().getId());
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        p = cb.and(cb.equal(root.get(entry.getKey()), entry.getValue()));
    }
    cq.where(p);
    TypedQuery<T> query = this.getEntityManager().createQuery(cq);
    return (T) query.getSingleResult();
}

From source file:net.nan21.dnet.core.business.service.entity.AbstractEntityReadService.java

/**
 * Find a list of entities of the given type, using as filter criteria the
 * specified list of attribute values.// w ww . java 2s.co  m
 * 
 * @param entityClass
 * @param params
 * @return
 * @throws BusinessException
 */
public <T> List<T> findEntitiesByAttributes(Class<T> entityClass, Map<String, Object> params) {
    CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);
    cq.select(root);
    Assert.notNull(params);
    Predicate p = null;
    if (entityClass.isAssignableFrom(IModelWithClientId.class)) {
        p = cb.equal(root.get("clientId"), Session.user.get().getClient().getId());
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        p = cb.and(cb.equal(root.get(entry.getKey()), entry.getValue()));
    }
    cq.where(p);
    TypedQuery<T> query = this.getEntityManager().createQuery(cq);
    return (List<T>) query.getResultList();
}

From source file:org.openmeetings.app.data.basic.dao.LdapConfigDaoImpl.java

public List<LdapConfig> getLdapConfigs(int start, int max, String orderby, boolean asc) {
    try {/*from   w w  w . j a va 2s.c  om*/
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<LdapConfig> cq = cb.createQuery(LdapConfig.class);
        Root<LdapConfig> c = cq.from(LdapConfig.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        cq.where(condition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<LdapConfig> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<LdapConfig> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getLdapConfigs]", ex2);
    }
    return null;
}

From source file:net.groupbuy.dao.impl.OrderDaoImpl.java

public Page<Order> findPage(Member member, Pageable pageable) {
    if (member == null) {
        return new Page<Order>(Collections.<Order>emptyList(), 0, pageable);
    }//from   w  ww. j  ava 2s.co m
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);
    criteriaQuery.where(criteriaBuilder.equal(root.get("member"), member));
    return super.findPage(criteriaQuery, pageable);
}