Example usage for org.hibernate.criterion DetachedCriteria setProjection

List of usage examples for org.hibernate.criterion DetachedCriteria setProjection

Introduction

In this page you can find the example usage for org.hibernate.criterion DetachedCriteria setProjection.

Prototype

public DetachedCriteria setProjection(Projection projection) 

Source Link

Document

Set the projection to use.

Usage

From source file:mitm.common.sms.hibernate.SMSGatewayDAO.java

License:Open Source License

/**
 * Returns the entry that has the oldest try date and not after notAfter. If there is no such entry null
 * is returned./*  w w w  . j  av a 2  s . c  o  m*/
 */
@SuppressWarnings("unchecked")
public SMSGatewayEntity getNextAvailable(Date notAfter) {
    DetachedCriteria minDateCriteria = createDetachedCriteria(entityName);

    /*
     * Create a criteria to get the oldest dateLastTry
     */
    minDateCriteria.setProjection(Projections.min(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()));

    Criteria criteria = createCriteria(entityName);

    criteria.add(Restrictions.or(
            Property.forName(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()).eq(minDateCriteria),
            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

    /*
     * We only want entries that are older than notAfter or have no dateLastTry yet. The reason for notAfter is
     * that we do not want to try too fast in succession. By setting notAfter in the past we can make sure that
     * we only get entries that are not recently been updated.
     */
    criteria.add(Restrictions.or(Restrictions.le(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn(), notAfter),
            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

    SMSGatewayEntity next = null;

    List<SMSGatewayEntity> found = criteria.list();

    if (found != null && found.size() > 0) {
        next = found.get(0);
    }

    return next;
}

From source file:models.db.acentera.impl.ProjectProvidersImpl.java

License:Open Source License

public static Set<ProjectRegions> getRegionsAvailables(Set<ProjectProvidersRegions> regions) {

    Session s = (Session) HibernateSessionFactory.getSession();

    DetachedCriteria msgFromCriteria = DetachedCriteria.forClass(DO_REGIONS.class);
    ProjectionList properties = Projections.projectionList();
    properties.add(Projections.groupProperty("slug"));
    msgFromCriteria.setProjection(properties);

    Criteria criteria = s.createCriteria(DO_REGIONS.class);
    criteria.add(Subqueries.propertiesIn(new String[] { "slug" }, msgFromCriteria));

    List<DO_REGIONS> list = criteria.list();

    HashSet<ProjectRegions> regionsSet = new HashSet<ProjectRegions>();
    Iterator<ProjectProvidersRegions> ppr = regions.iterator();
    while (ppr.hasNext()) {
        ProjectProvidersRegions item = ppr.next();

        boolean bFound = false;
        Iterator<DO_REGIONS> itrReg = list.iterator();
        while (itrReg.hasNext() && !bFound) {
            DO_REGIONS r = itrReg.next();
            try {
                if (r.getSlug().compareTo(item.getProjectRegions().getSlug()) == 0) {
                    bFound = true;//  www . j ava  2  s .co m
                }
            } catch (Exception ew) {
                ew.printStackTrace();
            }
        }
        if (bFound) {
            regionsSet.add(item.getProjectRegions());
        }
    }
    return regionsSet;

}

From source file:net.neurowork.cenatic.centraldir.dao.impl.HibernateOrganizacionDaoImpl.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/* ww w . j  ava2s.  c  o  m*/
public Integer getTotalOrganizaciones() throws DaoException {
    if (logger.isTraceEnabled())
        logger.trace("Hibernate Searching Total Organizaciones");
    DetachedCriteria criteria = DetachedCriteria.forClass(Organizacion.class);

    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.rowCount());
    criteria.setProjection(projList);

    List result = getHibernateTemplate().findByCriteria(criteria);
    if (result != null)
        return (Integer) result.get(0);
    return 0;
}

From source file:net.neurowork.cenatic.centraldir.dao.impl.HibernateSateliteDaoImpl.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/* w w  w.  j  a  v a2s  .co m*/
public Integer getOrganizacionesCount(Satelite satelite) throws DaoException {
    if (logger.isTraceEnabled())
        logger.trace("Hibernate Searching Total Organizaciones");
    DetachedCriteria criteria = DetachedCriteria.forClass(OrganizacionSatelite.class);

    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.rowCount());
    criteria.setProjection(projList);
    criteria.add(Restrictions.eq("satelite", satelite));

    List result = getHibernateTemplate().findByCriteria(criteria);
    if (result != null)
        return (Integer) result.get(0);
    return 0;

}

From source file:net.purnama.pureff.dao.RateDao.java

public RateEntity getLastRate(CurrencyEntity currency) {
    DetachedCriteria maxQuery = DetachedCriteria.forClass(RateEntity.class);
    maxQuery.add(Restrictions.eq("currency", currency));
    maxQuery.setProjection(Projections.max("lastmodified"));

    Session session = this.sessionFactory.getCurrentSession();
    Criteria c = session.createCriteria(RateEntity.class);
    c.add(Restrictions.eq("currency", currency));
    c.add(Property.forName("lastmodified").eq(maxQuery));

    RateEntity rate = (RateEntity) c.uniqueResult();

    return rate;//from ww  w  .ja  v a 2s  .c om
}

From source file:net.webpasswordsafe.server.dao.PasswordDAOHibernate.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<Password> findPasswordByFuzzySearch(String query, User user, boolean activeOnly,
        Collection<Tag> tags, Match tagMatch) {
    //kludge to not use ilike on text column if MSSQL
    boolean isMSSQL = ((SessionFactoryImpl) getSessionFactory()).getDialect().toString().contains("SQLServer");
    Criteria crit = getSession().createCriteria(getPersistentClass());
    crit.setFetchMode("tags", FetchMode.JOIN);
    crit.add(Restrictions.or(/*from   w  ww .ja v a  2  s .c  om*/
            Restrictions.or(Restrictions.ilike("name", query, MatchMode.ANYWHERE),
                    Restrictions.ilike("username", query, MatchMode.ANYWHERE)),
            isMSSQL ? Restrictions.like("notes", query, MatchMode.ANYWHERE)
                    : Restrictions.ilike("notes", query, MatchMode.ANYWHERE)));
    if (activeOnly) {
        crit.add(Restrictions.eq("active", true));
    }
    Criterion tagsCriterion = null;
    for (Tag tag : tags) {
        Criterion tc = Restrictions.sqlRestriction(
                "? in (select tag_id from password_tags where password_id = {alias}.id)", tag.getId(),
                StandardBasicTypes.LONG);
        if (null == tagsCriterion) {
            tagsCriterion = tc;
        } else {
            tagsCriterion = tagMatch.equals(Match.AND) ? Restrictions.and(tagsCriterion, tc)
                    : Restrictions.or(tagsCriterion, tc);
        }
    }
    if (tagsCriterion != null)
        crit.add(tagsCriterion);
    crit.createAlias("permissions", "pm");
    crit.add(Restrictions.in("pm.accessLevel",
            new String[] { AccessLevel.READ.name(), AccessLevel.WRITE.name(), AccessLevel.GRANT.name() }));
    if (!authorizer.isAuthorized(user, Function.BYPASS_PASSWORD_PERMISSIONS.name())) {
        DetachedCriteria groupQuery = DetachedCriteria.forClass(Group.class);
        groupQuery.setProjection(Projections.id());
        groupQuery.createCriteria("users", "u").add(Restrictions.eq("u.id", user.getId()));
        crit.add(Restrictions.or(Restrictions.eq("pm.subject", user),
                Subqueries.propertyIn("pm.subject", groupQuery)));
    }
    crit.addOrder(Order.asc("name"));
    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return crit.list();
}

From source file:nl.b3p.viewer.admin.stripes.AttributeActionBean.java

License:Open Source License

public Resolution getGridData() throws JSONException {
    JSONArray jsonData = new JSONArray();

    List<SimpleFeatureType> featureTypes = new ArrayList();
    if (simpleFeatureTypeId != null && simpleFeatureTypeId != -1) {
        SimpleFeatureType sft = (SimpleFeatureType) Stripersist.getEntityManager().find(SimpleFeatureType.class,
                simpleFeatureTypeId);//from   w w  w  .j  av  a  2s  . c om
        if (sft != null) {
            featureTypes.add(sft);
        }
    } else if (featureSourceId != null && featureSourceId != -1) {
        FeatureSource fc = (FeatureSource) Stripersist.getEntityManager().find(FeatureSource.class,
                featureSourceId);
        featureTypes = fc.getFeatureTypes();
    }

    String filterAlias = "";
    String filterAttribuut = "";
    String filterType = "";
    /* 
     * FILTERING: filter is delivered by frontend as JSON array [{property, value}]
     * for demo purposes the value is now returned, ofcourse here should the DB
     * query be built to filter the right records
     */
    if (this.getFilter() != null) {
        for (int k = 0; k < this.getFilter().length(); k++) {
            JSONObject j = this.getFilter().getJSONObject(k);
            String property = j.getString("property");
            String value = j.getString("value");
            if (property.equals("alias")) {
                filterAlias = value;
            }
            if (property.equals("attribute")) {
                filterAttribuut = value;
            }
            if (property.equals("type")) {
                filterType = value;
            }
        }
    }

    Session sess = (Session) Stripersist.getEntityManager().getDelegate();
    Criteria c = sess.createCriteria(AttributeDescriptor.class);

    /* Sorting is delivered by the frontend
     * as two variables: sort which holds the column name and dir which
     * holds the direction (ASC, DESC).
     */
    if (sort != null && dir != null) {
        Order order = null;
        if (sort.equals("attribute")) {
            sort = "name";
        }
        if (dir.equals("ASC")) {
            order = Order.asc(sort);
        } else {
            order = Order.desc(sort);
        }
        order.ignoreCase();
        c.addOrder(order);
    }

    if (filterAlias != null && filterAlias.length() > 0) {
        Criterion aliasCrit = Restrictions.ilike("alias", filterAlias, MatchMode.ANYWHERE);
        c.add(aliasCrit);
    }
    if (filterAttribuut != null && filterAttribuut.length() > 0) {
        Criterion attribuutCrit = Restrictions.ilike("name", filterAttribuut, MatchMode.ANYWHERE);
        c.add(attribuutCrit);
    }
    if (filterType != null && filterType.length() > 0) {
        Criterion typeCrit = Restrictions.ilike("type", filterType, MatchMode.ANYWHERE);
        c.add(typeCrit);
    }

    if (featureTypes != null && featureTypes.size() > 0) {
        /* Criteria for the all attribute descriptor ids of the feature types 
         * in featureTypes
         */
        DetachedCriteria c2 = DetachedCriteria.forClass(SimpleFeatureType.class);
        Collection ftIds = new ArrayList<Long>();
        for (SimpleFeatureType sft : featureTypes) {
            ftIds.add(sft.getId());
        }
        c2.add(Restrictions.in("id", ftIds));
        c2.createAlias("attributes", "attr");
        c2.setProjection(Projections.property("attr.id"));

        c.add(org.hibernate.criterion.Property.forName("id").in(c2));
    }
    int rowCount = c.list().size();

    if (limit > 0) {
        c.setMaxResults(limit);
    }
    c.setFirstResult(start);

    List attributes = c.list();

    for (Iterator it = attributes.iterator(); it.hasNext();) {
        AttributeDescriptor attr = (AttributeDescriptor) it.next();

        JSONObject j = this.getGridRow(attr.getId().intValue(), attr.getAlias(), attr.getName(),
                attr.getType());
        jsonData.put(j);
    }

    final JSONObject grid = new JSONObject();
    grid.put("totalCount", rowCount);
    grid.put("gridrows", jsonData);

    return new StreamingResolution("application/json") {
        @Override
        public void stream(HttpServletResponse response) throws Exception {
            response.getWriter().print(grid.toString());
        }
    };
}

From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java

License:Open Source License

public Resolution getAttributesList() throws JSONException {
    JSONArray jsonData = new JSONArray();

    List<SimpleFeatureType> featureTypes = new ArrayList();
    if (simpleFeatureTypeId != null && simpleFeatureTypeId != -1) {
        SimpleFeatureType sft = (SimpleFeatureType) Stripersist.getEntityManager().find(SimpleFeatureType.class,
                simpleFeatureTypeId);//from w ww. ja va 2 s .com
        if (sft != null) {
            featureTypes.add(sft);
        }
    } else {
        throw new IllegalArgumentException("No simpleFeatureType id provided");
    }

    Session sess = (Session) Stripersist.getEntityManager().getDelegate();
    Criteria c = sess.createCriteria(AttributeDescriptor.class);

    /* Criteria for the all attribute descriptor ids of the feature types 
     * in featureTypes
     */
    DetachedCriteria c2 = DetachedCriteria.forClass(SimpleFeatureType.class);
    Collection ftIds = new ArrayList<Long>();
    for (SimpleFeatureType sft : featureTypes) {
        ftIds.add(sft.getId());
    }
    c2.add(Restrictions.in("id", ftIds));
    c2.createAlias("attributes", "attr");
    c2.setProjection(Projections.property("attr.id"));

    c.add(org.hibernate.criterion.Property.forName("id").in(c2));
    int rowCount = c.list().size();

    List<AttributeDescriptor> attrs = c.list();

    for (Iterator<AttributeDescriptor> it = attrs.iterator(); it.hasNext();) {
        AttributeDescriptor attr = it.next();
        boolean indexChecked = false;
        boolean resultChecked = false;
        if (solrConfiguration != null) {
            for (AttributeDescriptor configAttribute : solrConfiguration.getIndexAttributes()) {
                if (configAttribute.getId() == attr.getId()) {
                    indexChecked = true;
                    break;
                }
            }
            for (AttributeDescriptor resultAttribute : solrConfiguration.getResultAttributes()) {
                if (resultAttribute.getId() == attr.getId()) {
                    resultChecked = true;
                    break;
                }
            }
        }
        JSONObject j = new JSONObject();
        j.put("id", attr.getId().intValue());
        j.put("alias", attr.getAlias());
        j.put("attribute", attr.getName());
        j.put("indexChecked", indexChecked);
        j.put("resultChecked", resultChecked);
        jsonData.put(j);
    }

    final JSONObject grid = new JSONObject();
    grid.put("totalCount", rowCount);
    grid.put("gridrows", jsonData);

    return new StreamingResolution("application/json") {
        @Override
        public void stream(HttpServletResponse response) throws Exception {
            response.getWriter().print(grid.toString());
        }
    };
}

From source file:org.ambraproject.rhino.service.impl.ArticleCrudServiceImpl.java

License:Open Source License

@Override
public Collection<String> getArticleDoisForDateRange(int pageNumber, int pageSize, SortOrder sortOrder,
        Optional<LocalDateTime> fromDate, Optional<LocalDateTime> toDate) {
    final long totalArticles = hibernateTemplate.execute(session -> {
        final Query query = session.createQuery("select count(*) from Article");
        final Long count = (Long) query.uniqueResult();
        return count;
    });/*  www. ja va2  s  . c  o m*/

    if (totalArticles > 0L) {
        pageNumber = max(pageNumber, 1);
        final int maxResults = min(pageSize, MAX_PAGE_SIZE);
        final int firstResult = (pageNumber - 1) * maxResults;

        if (LOG.isDebugEnabled()) {
            LOG.debug("pageNumber: {}, pageSize: {}", pageNumber, pageSize);
            LOG.debug("firstResult: {}, maxResults: {}", firstResult, maxResults);
            LOG.debug("sortOrder: {}", sortOrder);
        }

        if (firstResult < totalArticles) {
            final DetachedCriteria criteria = DetachedCriteria.forClass(Article.class);
            final ProjectionList projections = Projections.projectionList();
            projections.add(Projections.property("doi" /* propertyName */));
            criteria.setProjection(projections);

            // Set restrictions for filtering on date range, if any.
            if (fromDate.isPresent()) {
                criteria.add(Restrictions.ge("created" /* propertyName */,
                        java.sql.Timestamp.valueOf(fromDate.get())));
            }
            if (toDate.isPresent()) {
                criteria.add(Restrictions.le("created" /* propertyName */,
                        java.sql.Timestamp.valueOf(toDate.get())));
            }

            if (sortOrder == SortOrder.OLDEST) {
                criteria.addOrder(Order.asc("created" /* propertyName */));
            } else {
                criteria.addOrder(Order.desc("created" /* propertyName */));
            }

            @SuppressWarnings("unchecked")
            final List<String> articleDois = (List<String>) hibernateTemplate.findByCriteria(criteria,
                    firstResult, maxResults);
            return articleDois;
        }
    }
    return ImmutableList.of();
}

From source file:org.broadleafcommerce.cms.common.AbstractContentService.java

License:Apache License

private <T> void addSandboxCriteria(SandBox sandbox, Criteria c, Class<T> type, String originalIdProperty) {
    Criterion originalSandboxExpression = Restrictions.eq("originalSandBox", sandbox);
    Criterion currentSandboxExpression = Restrictions.eq("sandbox", sandbox);
    Criterion userSandboxExpression = Restrictions.or(currentSandboxExpression, originalSandboxExpression);
    Criterion productionSandboxExpression = null;
    if (sandbox.getSite() == null || sandbox.getSite().getProductionSandbox() == null) {
        productionSandboxExpression = Restrictions.isNull("sandbox");
    } else {/*from www.java  2s  .  com*/
        productionSandboxExpression = Restrictions.eq("sandbox", sandbox.getSite().getProductionSandbox());
    }

    if (productionSandboxExpression != null) {
        c.add(Restrictions.or(userSandboxExpression, productionSandboxExpression));
    } else {
        c.add(userSandboxExpression);
    }

    // Build a sub-query to exclude items from production that are also in my sandbox.
    // (e.g. my sandbox always wins even if the items in my sandbox don't match the
    // current criteria.)
    //
    // This subquery prevents the following:
    // 1.  Duplicate items (one for sbox, one for prod)
    // 2.  Filter issues where the production item qualifies for the passed in criteria
    //     but has been modified so that the item in the sandbox no longer does.
    // 3.  Inverse of #2.
    DetachedCriteria existsInSboxCriteria = DetachedCriteria.forClass(type, "sboxItem");
    existsInSboxCriteria.add(userSandboxExpression);
    existsInSboxCriteria.add(Restrictions.eq("archivedFlag", false));
    String outerAlias = c.getAlias();
    existsInSboxCriteria.add(Property.forName(outerAlias + ".id").eqProperty("sboxItem." + originalIdProperty));
    existsInSboxCriteria.setProjection(Projections.id());
    c.add(Subqueries.notExists(existsInSboxCriteria));
}