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.sfs.captor.controller.RequirementAction.java

/**
 * load requirements/*from w  ww  .j av a 2 s . c o  m*/
 */
private void loadList() throws UCMException {

    Set<String> versions = this.projectService.findActiveProductReleaseVersions(this.authUser, this.project);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Requirement> c = cb.createQuery(Requirement.class);
    Root<Requirement> obj = c.from(Requirement.class);
    c.select(obj).where(cb.equal(obj.get("project"), this.project),
            obj.get("productRelease").get("version").in(versions)).orderBy(cb.asc(obj.get("id")));
    this.requirements = em.createQuery(c).getResultList();

}

From source file:com.sfs.captor.controller.RequirementAction.java

/**
 * find tests associated with this artifact
 *//*from  w w  w .  j a v  a2  s  . c  o  m*/
private List<RequirementRuleTest> findRequirementRuleTests(RequirementRule requirementRule) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<RequirementRuleTest> c = cb.createQuery(RequirementRuleTest.class);
    Root<RequirementRuleTest> obj = c.from(RequirementRuleTest.class);
    c.select(obj).where(cb.equal(obj.get("requirementRule"), requirementRule));
    return em.createQuery(c).getResultList();
}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/**
 * /*  www. ja  v  a 2  s. com*/
 * @param metric
 * @return
 * @throws uQasarException
 */
public int countMeasurementsPerProjectByMetricWithinPeriod(Project project, String metric, String period)
        throws uQasarException {
    logger.info("Count measurements for metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);
    Predicate condition1 = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
    Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.project), project);

    Date from = getDateForPeriod(period);
    Date to = DateTime.now().toDate();
    Predicate condition3 = cb.between(root.get(JiraMetricMeasurement_.timeStamp), from, to);
    Predicate condition4 = cb.and(condition1, condition2, condition3);
    query.where(condition4);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    Integer res = em.createQuery(query).getResultList().size();
    logger.info("Results' count: " + res);
    return res;
}

From source file:in.bookmylab.jpa.JpaDAO.java

public List<ResourceBooking> searchResourceBooking(BookingSearchInput si) {
    EntityManager em = emf.createEntityManager();
    try {// w  ww  .ja va 2s . com
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ResourceBooking> cq = cb.createQuery(ResourceBooking.class);
        Root<ResourceBooking> s = cq.from(ResourceBooking.class);
        List<Predicate> pred = new ArrayList<Predicate>();
        if (si.userId != null) {
            pred.add(cb.equal(s.<User>get("user").<Integer>get("userId"), si.userId));
        }
        if (si.bookingDateFrom != null) {
            pred.add(cb.greaterThanOrEqualTo(s.<Date>get("bookingDate"), si.bookingDateFrom));
        }
        if (si.bookingDateTo != null) {
            pred.add(cb.lessThanOrEqualTo(s.<Date>get("bookingDate"), si.bookingDateTo));
        }
        if (!StringUtils.isEmpty(si.lab)) {
            pred.add(cb.equal(s.<String>get("lab"), si.lab));
        }
        if (!StringUtils.isEmpty(si.status)) {
            pred.add(cb.equal(s.<String>get("status"), si.status));
        }
        cq.select(s).where(pred.toArray(new Predicate[] {}));
        return em.createQuery(cq).getResultList();
    } finally {
        em.close();
    }
}

From source file:ch.sdi.plugins.oxwall.job.OxSqlJob.java

/**
 * @see ch.sdi.core.intf.SqlJob#isAlreadyPresent(ch.sdi.core.impl.data.Person)
 *///w w w. j a va2 s .com
@Override
public boolean isAlreadyPresent(Person<?> aPerson) throws SdiException {
    if (myDryRun && !myCheckDuplicateOnDryRun) {
        myLog.debug("DryRun is active. Not checking for duplicate person");
        return false;
    } // if myDryRun

    CriteriaBuilder cb = myEntityManager.getCriteriaBuilder();

    CriteriaQuery<OxUser> criteria = cb.createQuery(OxUser.class);
    Root<OxUser> root = criteria.from(OxUser.class);
    ParameterExpression<String> mailParam = cb.parameter(String.class);
    criteria.select(root).where(cb.equal(root.get("email"), mailParam));

    TypedQuery<OxUser> queryEMail = myEntityManager.createQuery(criteria);

    queryEMail.setParameter(mailParam, aPerson.getEMail());
    List<OxUser> results = queryEMail.getResultList();

    if (results.size() > 0) {
        myLog.debug("given Person is already present: " + results.get(0));
        return true;
    } // if results.size() > 0

    return false;
}

From source file:ch.sdi.plugins.oxwall.job.OxSqlJob.java

/**
 * Checks if the given hash is present in the ow_base_avatar table
 *
 * @param aHash//from www .j av  a2 s. com
 * @return
 */
public boolean isAvatarHashPresent(Long aHash) {
    if (myDryRun) {
        myLog.debug("DryRun is active. Not checking for duplicate avatar hash");
        return false;
    } // if myDryRun

    CriteriaBuilder cb = myEntityManager.getCriteriaBuilder();

    CriteriaQuery<OxAvatar> criteria = cb.createQuery(OxAvatar.class);
    Root<OxAvatar> root = criteria.from(OxAvatar.class);
    ParameterExpression<Long> avatarParam = cb.parameter(Long.class);
    avatarParam = cb.parameter(Long.class);
    criteria.select(root).where(cb.equal(root.get("hash"), avatarParam));
    TypedQuery<OxAvatar> query = myEntityManager.createQuery(criteria);
    query.setParameter(avatarParam, aHash);
    List<OxAvatar> results = query.getResultList();

    if (results.size() > 0) {
        myLog.debug("given avatar hash is already present: " + aHash);
        return true;
    } // if results.size() > 0

    return false;
}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/** 
 * @param metric//w  w  w  .java 2 s.  com
 * @param project
 * @return
 * @throws uQasarException
 */
public List<JiraMetricMeasurement> getMeasurementsPerProjectByMetricWithLatestDate(Project project,
        String metric) throws uQasarException {
    logger.info("Count measurements for project + " + project.getAbbreviatedName() + " and metric: " + metric
            + "with latest date");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);

    Predicate condition1 = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
    Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.project), project);

    Predicate condition4 = cb.and(condition1, condition2);
    query.where(condition4);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    List<JiraMetricMeasurement> returnResults = em.createQuery(query).getResultList();

    Date newDate = null;
    for (JiraMetricMeasurement jMM : returnResults) {
        if (newDate == null || jMM.getTimeStamp().compareTo(newDate) > 0) {
            newDate = jMM.getTimeStamp();
        }

    }

    return getMeasurementsByMetricAndDate(metric, newDate);
}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/**
 * /* w ww.java2  s  .  c  om*/
 * @param metric
 * @return
 * @throws uQasarException
 */
public List<JiraMetricMeasurement> getMeasurementsPerProjectByMetricWithinPeriod(Project project, String metric,
        String period) throws uQasarException {

    List<JiraMetricMeasurement> measurements = new ArrayList<>();
    if (project != null && metric != null && period != null) {
        logger.info(
                "Count measurements for project + " + project.getAbbreviatedName() + " and metric: " + metric);

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
        Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);

        Predicate condition1 = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
        Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.project), project);

        Date from = getDateForPeriod(period);
        Date to = DateTime.now().toDate();
        Predicate condition3 = cb.between(root.get(JiraMetricMeasurement_.timeStamp), from, to);
        //      System.out.println("from:"+from);
        //      System.out.println("to:"+to);

        Predicate condition4 = cb.and(condition1, condition2, condition3);
        query.where(condition4);
        query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
        measurements = em.createQuery(query).getResultList();
    }

    return measurements;
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Add the {@link SystemUserLogType} to the database.
 *
 * @param log/*  w w w  . ja v  a2 s.c  o m*/
 *            the {@link SystemUserLogType} to add.
 */
private void addChannelInvocation(final SystemUserLogType log) {
    /* Setup context and version. */
    log.setContext(this.getContextName());
    log.setVersion(this.getContextVersion());
    if (log.getUserName() != null && log.getUserName().trim().length() == 0) {
        log.setUserName(null);
    }

    /* Setup to search existing one. */
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);

    final List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.context), log.getContext()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.version), log.getVersion()));
    if (log.getUserName() == null) {
        predicates.add(cb.isNull(c.<String>get(SystemUserLogType_.userName)));
    } else {
        predicates.add(cb.equal(c.<String>get(SystemUserLogType_.userName), log.getUserName()));
    }
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.serviceName), log.getServiceName()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.operationName), log.getOperationName()));
    predicates.add(cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(log.getLogDateItem()),
            getDayEnd(log.getLogDateItem())));

    q.where(predicates.toArray(new Predicate[predicates.size()]));
    q.orderBy(cb.desc(c.<Long>get(SystemUserLogType_.hjid)));
    TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);

    SystemUserLogType persistence = null;
    synchronized (StatisticsLoggingDao.class) {
        try {
            persistence = typedQuery.getSingleResult();
            if (persistence == null) {
                /* Not found -> persist */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            } else {
                /* Found -> add and merge */
                this.setupSystemUserLog(persistence, log);
                this.em.merge(persistence);
            }
        } catch (final NoResultException e) {
            /* Not found -> persist */
            persistence = log;
            this.setupSystemUserLog(persistence, null);
            this.em.persist(persistence);
        } catch (final NonUniqueResultException e) {
            /* Found more */
            typedQuery = this.em.createQuery(q);
            final List<SystemUserLogType> list = typedQuery.getResultList();
            SystemUserLogType l;
            for (int i = 0; i < list.size(); i++) {
                l = list.get(i);
                if (persistence == null && l.getHjid() != null) {
                    persistence = l;
                    break;
                }
            }
            if (persistence != null) {
                /* Found more -> condense to first valid one -> merge. */
                this.setupSystemUserLog(persistence, log);
                for (int i = list.size() - 1; i >= 0; i--) {
                    l = list.get(i);
                    if (l != null && l.getHjid() != null) {
                        if (persistence.getHjid().equals(l.getHjid())) {
                        } else {
                            this.setupSystemUserLog(persistence, l);
                            list.remove(i);
                            this.em.remove(l);
                        }
                    }
                }
                this.em.merge(persistence);
            } else {
                /* Found more -> no valid one in list -> persist. */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            }
        }
    }
    this.logger.debug("addChannelInvocation SystemUserLog {} {} {} {} {} {}",
            this.contextNameProvider.getContextName(), this.contextNameProvider.getContextVersion(),
            String.valueOf(persistence.getUserName()), persistence.getServiceName(),
            persistence.getOperationName(), persistence.getLogDate().toXMLFormat());
}

From source file:com.sishuok.es.common.repository.support.SimpleBaseRepository.java

/**
 * Creates a new count query for the given {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param spec can be {@literal null}.//from   w  w w  . jav a 2  s . c o  m
 * @return
 */
private TypedQuery<Long> getCountQuery(Specification<M> spec) {

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);

    Root<M> root = applySpecificationToCriteria(spec, query);

    if (query.isDistinct()) {
        query.select(builder.countDistinct(root));
    } else {
        query.select(builder.count(root));
    }

    TypedQuery<Long> q = em.createQuery(query);
    repositoryHelper.applyEnableQueryCache(q);
    return q;
}