Example usage for javax.persistence EntityManager getCriteriaBuilder

List of usage examples for javax.persistence EntityManager getCriteriaBuilder

Introduction

In this page you can find the example usage for javax.persistence EntityManager getCriteriaBuilder.

Prototype

public CriteriaBuilder getCriteriaBuilder();

Source Link

Document

Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.

Usage

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*from  w w  w.  j a va 2  s.  com*/
 */
@Override
public <T extends BaseEntity> int deleteAll(Class<T> entity) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        int rowsDeleted = em.createQuery(em.getCriteriaBuilder().createCriteriaDelete(entity)).executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("deleteAll: No. of rows deleted: [{}]", rowsDeleted);
        return rowsDeleted;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java

/**
 * Default constructor./*  w w  w.  ja va 2  s.  c  o m*/
 * @param entityManager
 * @param classificationHelper
 */
public ArtificerToHibernateQueryVisitor(EntityManager entityManager, ClassificationHelper classificationHelper)
        throws ArtificerException {
    super(classificationHelper);

    this.entityManager = entityManager;
    criteriaBuilder = entityManager.getCriteriaBuilder();
}

From source file:fi.vm.sade.organisaatio.dao.impl.OrganisaatioDAOImpl.java

@Override
public List<Organisaatio> findByOidList(List<String> oidList, int maxResults) {
    LOG.debug("findByOidList({}, {})", oidList, maxResults);

    // first drop nulls from oidList
    List<String> oidListFiltered = new ArrayList<>();
    for (String oid : oidList) {
        if (oid != null) {
            oidListFiltered.add(oid);/*  ww  w  .j av  a 2 s. com*/
        }
    }

    // perform query
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Organisaatio> query = cb.createQuery(Organisaatio.class);
    Root<Organisaatio> organisaatio = query.from(Organisaatio.class);
    query.orderBy(cb.asc(organisaatio.get("nimihaku")));
    Predicate where = cb.in(organisaatio.get("oid")).value(oidListFiltered);
    query.where(where);
    return getEntityManager().createQuery(query).setMaxResults(maxResults).getResultList();

}

From source file:org.opencastproject.messages.MailService.java

public List<MessageTemplate> findMessageTemplates(TemplateMessageQuery query) {
    EntityManager em = null;
    List<MessageTemplate> messageTemplates = new ArrayList<MessageTemplate>();

    try {//from  w w w  .j a  v  a 2 s.c  o m
        em = emf.createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<MessageTemplateDto> q = cb.createQuery(MessageTemplateDto.class);
        Root<MessageTemplateDto> messageTemplateRoot = q.from(MessageTemplateDto.class);

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

        q.select(messageTemplateRoot);

        String orgId = securityService.getOrganization().getId();
        predicates.add(cb.equal(messageTemplateRoot.get("organization"), orgId));

        if (!query.isIncludeHidden())
            predicates.add(cb.isFalse(messageTemplateRoot.get("hidden").as(Boolean.class)));

        if (StringUtils.isNotEmpty(query.getName()))
            predicates.add(cb.equal(messageTemplateRoot.get("name"), query.getName()));

        if (StringUtils.isNotEmpty(query.getCreator()))
            predicates.add(cb.equal(messageTemplateRoot.get("creator"), query.getCreator()));

        if (query.getType() != null)
            predicates.add(
                    cb.equal(messageTemplateRoot.get("type").as(TemplateType.Type.class), query.getType()));

        if (StringUtils.isNotEmpty(query.getFullText())) {
            List<Predicate> fullTextPredicates = new ArrayList<Predicate>();
            fullTextPredicates
                    .add(cb.like(messageTemplateRoot.<String>get("name"), "%" + query.getFullText() + "%"));
            fullTextPredicates
                    .add(cb.like(messageTemplateRoot.<String>get("subject"), "%" + query.getFullText() + "%"));
            fullTextPredicates
                    .add(cb.like(messageTemplateRoot.<String>get("body"), "%" + query.getFullText() + "%"));
            predicates.add(cb.or(fullTextPredicates.toArray(new Predicate[fullTextPredicates.size()])));
        }

        q.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

        TypedQuery<MessageTemplateDto> typedQuery = em.createQuery(q);
        List<MessageTemplateDto> messageTemplatesDto = typedQuery.getResultList();

        for (MessageTemplateDto mt : messageTemplatesDto) {
            messageTemplates.add(mt.toMessageTemplate(userDirectoryService));
        }

        return messageTemplates;
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private static List<Long> filterResourceIdsByLastUpdated(EntityManager theEntityManager,
        final DateRangeParam theLastUpdated, Collection<Long> thePids) {
    CriteriaBuilder builder = theEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    List<Predicate> lastUpdatedPredicates = createLastUpdatedPredicates(theLastUpdated, builder, from);
    lastUpdatedPredicates.add(from.get("myId").as(Long.class).in(thePids));

    cq.where(SearchBuilder.toArray(lastUpdatedPredicates));
    TypedQuery<Long> query = theEntityManager.createQuery(cq);

    List<Long> resultList = query.getResultList();
    return resultList;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> int getItemCount(Class<T> classObj) throws Exception {
    int returnValue = 0;

    EntityManager em = getEntityManager();

    try {//w  w w . j ava2s. c om

        // StringBuffer hsqlQuery = new StringBuffer();
        // hsqlQuery.append("select count(*) from ");
        // hsqlQuery.append(classObj.getCanonicalName());
        // hsqlQuery.append(" as o");
        // Query q = em.createQuery(hsqlQuery.toString());
        //
        // returnValue = ((Long) q.getSingleResult()).intValue();

        CriteriaBuilder qb = em.getCriteriaBuilder();
        CriteriaQuery<Long> cq = qb.createQuery(Long.class);
        cq.select(qb.count(cq.from(classObj)));

        Long res = em.createQuery(cq).getSingleResult();

        return res.intValue();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

public static void loadResourcesByPid(Collection<Long> theIncludePids,
        List<IBaseResource> theResourceListToPopulate, Set<Long> theRevIncludedPids,
        boolean theForHistoryOperation, EntityManager entityManager, FhirContext context, IDao theDao) {
    if (theIncludePids.isEmpty()) {
        return;//  w ww.  j  a  v  a2 s.co m
    }

    Map<Long, Integer> position = new HashMap<Long, Integer>();
    for (Long next : theIncludePids) {
        position.put(next, theResourceListToPopulate.size());
        theResourceListToPopulate.add(null);
    }

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ResourceTable> cq = builder.createQuery(ResourceTable.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.where(from.get("myId").in(theIncludePids));
    TypedQuery<ResourceTable> q = entityManager.createQuery(cq);

    for (ResourceTable next : q.getResultList()) {
        Class<? extends IBaseResource> resourceType = context.getResourceDefinition(next.getResourceType())
                .getImplementingClass();
        IBaseResource resource = (IBaseResource) theDao.toResource(resourceType, next, theForHistoryOperation);
        Integer index = position.get(next.getId());
        if (index == null) {
            ourLog.warn("Got back unexpected resource PID {}", next.getId());
            continue;
        }

        if (resource instanceof IResource) {
            if (theRevIncludedPids.contains(next.getId())) {
                ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put((IResource) resource,
                        BundleEntrySearchModeEnum.INCLUDE);
            } else {
                ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put((IResource) resource,
                        BundleEntrySearchModeEnum.MATCH);
            }
        } else {
            if (theRevIncludedPids.contains(next.getId())) {
                ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put((IAnyResource) resource,
                        BundleEntrySearchModeEnum.INCLUDE.getCode());
            } else {
                ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put((IAnyResource) resource,
                        BundleEntrySearchModeEnum.MATCH.getCode());
            }
        }

        theResourceListToPopulate.set(index, resource);
    }
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog210.java

/**
 * Delete STORM_REST_API component if HDP is upgraded past 2.2 and the
 * Component still exists./*from   w  w  w. ja  va2s  . c o m*/
 */
protected void removeStormRestApiServiceComponent() {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    Clusters clusters = ambariManagementController.getClusters();

    if (clusters != null) {
        Map<String, Cluster> clusterMap = clusters.getClusters();
        for (final Cluster cluster : clusterMap.values()) {
            StackId stackId = cluster.getCurrentStackVersion();
            if (stackId != null && stackId.getStackName().equals("HDP")
                    && VersionUtils.compareVersions(stackId.getStackVersion(), "2.2") >= 0) {

                executeInTransaction(new Runnable() {
                    @Override
                    public void run() {
                        ServiceComponentDesiredStateDAO dao = injector
                                .getInstance(ServiceComponentDesiredStateDAO.class);
                        ServiceComponentDesiredStateEntityPK entityPK = new ServiceComponentDesiredStateEntityPK();
                        entityPK.setClusterId(cluster.getClusterId());
                        entityPK.setServiceName("STORM");
                        entityPK.setComponentName("STORM_REST_API");
                        ServiceComponentDesiredStateEntity entity = dao.findByPK(entityPK);
                        if (entity != null) {
                            EntityManager em = getEntityManagerProvider().get();
                            CriteriaBuilder cb = em.getCriteriaBuilder();

                            try {
                                LOG.info("Deleting STORM_REST_API service component.");
                                CriteriaDelete<HostComponentStateEntity> hcsDelete = cb
                                        .createCriteriaDelete(HostComponentStateEntity.class);
                                CriteriaDelete<HostComponentDesiredStateEntity> hcdDelete = cb
                                        .createCriteriaDelete(HostComponentDesiredStateEntity.class);
                                CriteriaDelete<ServiceComponentDesiredStateEntity> scdDelete = cb
                                        .createCriteriaDelete(ServiceComponentDesiredStateEntity.class);

                                Root<HostComponentStateEntity> hcsRoot = hcsDelete
                                        .from(HostComponentStateEntity.class);
                                Root<HostComponentDesiredStateEntity> hcdRoot = hcdDelete
                                        .from(HostComponentDesiredStateEntity.class);
                                Root<ServiceComponentDesiredStateEntity> scdRoot = scdDelete
                                        .from(ServiceComponentDesiredStateEntity.class);

                                hcsDelete.where(cb.equal(hcsRoot.get("componentName"), "STORM_REST_API"));
                                hcdDelete.where(cb.equal(hcdRoot.get("componentName"), "STORM_REST_API"));
                                scdDelete.where(cb.equal(scdRoot.get("componentName"), "STORM_REST_API"));

                                em.createQuery(hcsDelete).executeUpdate();
                                em.createQuery(hcdDelete).executeUpdate();
                                em.createQuery(scdDelete).executeUpdate();
                            } catch (Exception e) {
                                LOG.warn("Error deleting STORM_REST_API service component. "
                                        + "This could result in issue with ambari server start. "
                                        + "Please make sure the STORM_REST_API component is deleted "
                                        + "from the database by running following commands:\n"
                                        + "delete from hostcomponentdesiredstate where component_name='STORM_REST_API';\n"
                                        + "delete from hostcomponentstate where component_name='STORM_REST_API';\n"
                                        + "delete from servicecomponentdesiredstate where component_name='STORM_REST_API';\n",
                                        e);
                            }
                        }
                    }
                });
            }
        }
    }
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> Long countBy(Class<T> clazz, JPAEntityFilter<T> filter) throws Exception {
    Long res = 0L;/*w w w  .  jav a  2  s  .  co m*/

    testClazz(clazz);

    EntityManager em = getEntityManager();

    try {

        if (filter != null) {

            // Source:
            // http://stackoverflow.com/questions/5349264/total-row-count-for-pagination-using-jpa-criteria-api

            CriteriaQuery<T> cq = filter.getCriteria(clazz, getEmf());

            // TypedQuery<T> q = em.createQuery(cq);
            //
            // q.setFirstResult(filter.getLimit() * filter.getPageNumber());
            // q.setMaxResults(filter.getLimit());
            //
            // res = Long.valueOf(q.getResultList().size());

            // CriteriaBuilder qb = em.getCriteriaBuilder();
            // CriteriaQuery<Long> countQuery = qb.createQuery(Long.class);
            // countQuery.select(qb.count(cq.from(clazz)));
            // // cq.where(/*your stuff*/);
            // return em.createQuery(cq).getSingleResult();

            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<Long> cqCount = builder.createQuery(Long.class);
            cqCount.select(builder.count(cqCount.from(clazz)));

            // Following line if commented causes
            // [org.hibernate.hql.ast.QuerySyntaxException: Invalid path:
            // 'generatedAlias1.enabled' [select count(generatedAlias0) from
            // xxx.yyy.zzz.Brand as generatedAlias0 where (
            // generatedAlias1.enabled=:param0 ) and (
            // lower(generatedAlias1.description) like :param1 )]]
            em.createQuery(cqCount);

            // filter.getCriteria(clazz, getEmf());
            cqCount.where(filter.getWherePredicate(clazz, getEmf()));

            res = em.createQuery(cqCount).getSingleResult();

        } else {
            // res = findAll(clazz);

            CriteriaBuilder qb = em.getCriteriaBuilder();
            CriteriaQuery<Long> cq = qb.createQuery(Long.class);
            cq.select(qb.count(cq.from(clazz)));
            // cq.where(/*your stuff*/);
            res = em.createQuery(cq).getSingleResult();

        }

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String)
 *//*from w  w  w.  ja  va 2  s  .c  o  m*/
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId) throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}