Example usage for org.hibernate.criterion Projections property

List of usage examples for org.hibernate.criterion Projections property

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections property.

Prototype

public static PropertyProjection property(String propertyName) 

Source Link

Document

A property value projection

Usage

From source file:com.photon.phresco.eshop.service.EShopService.java

License:Apache License

public Review getReviews(final int productId) throws EShopException {
    @SuppressWarnings("unchecked")
    Review review = (Review) template.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Review review = new Review();
            review.setProductId(productId);
            review.setUserId(1);/*from w  w w . j av a 2s.c  o  m*/
            List<KeyValue> ratings = new ArrayList<KeyValue>(5);
            Rating rating = new Rating();
            int total = 0;

            for (int i = 1; i <= 5; i++) {
                List<Integer> count = session.createCriteria(ReviewHBM.class)
                        .setProjection(Projections.rowCount()).add(Restrictions.eq("ratings", i))
                        .add(Restrictions.eq("productId", productId)).list();
                System.out.println("count = " + count);
                int totalRating = (int) count.get(0);
                total += totalRating;
                System.out.println("Total Rating = " + totalRating);
                // reviewHBM.setTotalRating(totalRating);
                KeyValue keyvalue = new KeyValue(i, totalRating);
                ratings.add(keyvalue);
                rating.setRating(ratings);
                // reviews.add(reviewHBM);
            }

            Criteria crit = session.createCriteria(ReviewHBM.class)
                    .add(Restrictions.eq("productId", productId));
            ProjectionList p1 = Projections.projectionList();
            p1.add(Projections.property("comment"));
            p1.add(Projections.property("ratings"));
            p1.add(Projections.property("commentDate"));
            p1.add(Projections.property("userId"));

            crit.setProjection(p1);

            List<Comment> list = crit.list();

            Iterator iter = list.iterator();
            List<Comment> comments = new ArrayList<Comment>();
            while (iter.hasNext()) {
                Object[] obj = (Object[]) iter.next();
                Comment comment = null;
                for (int i = 0; i < obj.length; i++) {
                    comment = new Comment();
                    comment.setComment(obj[0].toString());
                    comment.setRatings((Integer) obj[1]);
                    java.sql.Date sqlDate = (java.sql.Date) obj[2];
                    java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
                    comment.setCommentDate(utilDate);
                    comment.setUserid((Integer) obj[3]);
                    comments.add(comment);
                    Criteria criteria = session.createCriteria(UserHBM.class)
                            .add(Restrictions.eq("userId", (Integer) obj[3]));
                    ProjectionList p2 = Projections.projectionList();
                    p2.add(Projections.property("userName"));
                    criteria.setProjection(p2);

                    List listusername = criteria.list();
                    Iterator iter1 = listusername.iterator();
                    while (iter1.hasNext()) {
                        Object[] obj1 = (Object[]) iter.next();
                        for (int j = 0; j < obj1.length; j++) {
                            System.out.println("obj{j] value ---> " + obj1[j]);
                            comment.setUser((String) obj1[j]);
                        }
                    }
                }

            }

            int averateRating = ServiceUtil.getRating(total);
            review.setAverage(averateRating);
            review.setRatings(rating);
            review.setComments(comments);

            return review;
        }
    });

    return review;
}

From source file:com.qcadoo.model.api.search.SearchProjections.java

License:Open Source License

/**
 * Creates projection which add given field to the "SELECT" clause.
 * //from  w  w  w.ja  va 2  s  .c  o m
 * @param field
 *            field
 * @return projection
 */
public static SearchProjection field(final String field) {
    return new SearchProjectionImpl(Projections.property(field));
}

From source file:com.quix.aia.cn.imo.mapper.AamDataMaintenance.java

License:Open Source License

/**
 * <p>/*from   w  ww  . jav a2  s.  c om*/
 * This method retrieves agentName for particular agentId
 * </p>
 * 
 * @param agentId
 * @return String 
 * 
 */
public static String retrieveAgentName(String agentId) {
    String agentName = "";
    try {
        session = clientSessionFactory.openSession();
        transaction = session.beginTransaction();

        Criteria crit = session.createCriteria(AamData.class);
        if (null != agentId && !"".equals(agentId)) {
            crit.setProjection(Projections.property("agentName"));
            crit.add(Restrictions.eq("agentCode", agentId));
        }

        ArrayList list = (ArrayList) crit.setCacheable(true).list();
        if (list != null && list.size() > 0)
            agentName = (String) list.get(0);
    } catch (Exception he) {
        he.printStackTrace();

        LogsMaintenance logsMain = new LogsMaintenance();
        StringWriter errors = new StringWriter();
        he.printStackTrace(new PrintWriter(errors));
        logsMain.insertLogs("AamDataMaintenance", Level.SEVERE + "", errors.toString());
    } finally {
        session.close();
    }

    return agentName;
}

From source file:com.reignite.parser.Join.java

License:Open Source License

/**
 * Gets all the basic fields of the criteria entity
 * //  w w w  .j ava 2 s . c o  m
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IntrospectionException
 */
public void populateFields()
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, IntrospectionException {
    Class<?> clazz = Class.forName(entity);
    Method getter = clazz.getMethod("get" + Character.toUpperCase(name.charAt(0)) + name.substring(1));

    Class<?> joined = (Class<?>) ((ParameterizedType) getter.getGenericReturnType())
            .getActualTypeArguments()[0];

    ClassMetadata metadata = session.getSessionFactory().getClassMetadata(joined);
    expectedFields.add(name + "." + metadata.getIdentifierPropertyName());
    projections.add(Projections.property(name + "." + metadata.getIdentifierPropertyName()));
    for (String fieldName : metadata.getPropertyNames()) {
        Type type = metadata.getPropertyType(fieldName);
        if (!type.isAnyType() && !type.isAssociationType() && !type.isComponentType()
                && !type.isCollectionType()) {
            String field = name + "." + fieldName;
            expectedFields.add(field);
            projections.add(Projections.property(field));
        }
    }
}

From source file:com.reignite.query.StructuredQuery.java

License:Open Source License

private void processFields() throws ParserException {
    if (fields.size() > 0) {
        if (projections == null) {
            projections = Projections.projectionList();
        }/*  ww w . j a v a2 s.  c o  m*/
        for (String field : fields) {
            projections.add(Projections.property(field));
            expectedFields.add(field);
        }
        criteria.setProjection(projections);
    }
    if (hasJoin) {
        for (Join join : joins) {
            if (join.getProjections() == null) {
                join.setProjections(Projections.projectionList());
            }
            for (String field : fields) {
                join.getProjections().add(Projections.property(field));
                join.addExpectedField(field);
            }
            if (join.getFields().isEmpty()) {
                // get all the properties from the joined object
                try {
                    join.populateFields();
                } catch (Exception e) {
                    throw new ParserException("failed to create join object: " + e);
                }
            } else {
                for (String field : join.getFields()) {
                    join.getProjections().add(Projections.property(field));
                    join.addExpectedField(field);
                }
            }
            join.applyProjections();
        }
    }
}

From source file:com.romeikat.datamessie.core.base.dao.impl.AbstractEntityWithIdAndVersionDao.java

License:Open Source License

@Override
public TreeMap<Long, Long> getIdsWithVersion(final SharedSessionContract ssc, final Long firstId,
        final Integer maxResults) {
    // Query/*from  w w  w.j  a v a  2  s  .  c  o  m*/
    final EntityWithIdQuery<E> query = new EntityWithIdQuery<>(getEntityClass());
    if (firstId != null) {
        query.addRestriction(Restrictions.ge("id", firstId));
    }
    query.setMaxResults(maxResults);
    query.addOrder(Order.asc("id"));
    query.setResultTransformer(new AliasToBeanResultTransformer(IdAndVersion.class));

    // Done
    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("id"), "id");
    projectionList.add(Projections.property("version"), "version");
    @SuppressWarnings("unchecked")
    final List<IdAndVersion> idsAndVersions = (List<IdAndVersion>) query.listForProjection(ssc, projectionList);

    // Transform into map
    final TreeMap<Long, Long> result = transformIntoMap(idsAndVersions);
    return result;
}

From source file:com.romeikat.datamessie.core.base.dao.impl.AbstractEntityWithIdAndVersionDao.java

License:Open Source License

@Override
public TreeMap<Long, Long> getIdsWithVersion(final SharedSessionContract ssc, final Collection<Long> ids) {
    if (ids.isEmpty()) {
        return new TreeMap<Long, Long>();
    }//ww  w.ja  va 2s .c  om

    // Query
    final EntityWithIdQuery<E> query = new EntityWithIdQuery<>(getEntityClass());
    query.addRestriction(Restrictions.in("id", ids));
    query.setResultTransformer(new AliasToBeanResultTransformer(IdAndVersion.class));

    // Done
    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("id"), "id");
    projectionList.add(Projections.property("version"), "version");
    @SuppressWarnings("unchecked")
    final List<IdAndVersion> idsAndVersions = (List<IdAndVersion>) query.listForProjection(ssc, projectionList);

    // Transform into map
    final TreeMap<Long, Long> result = transformIntoMap(idsAndVersions);
    return result;
}

From source file:com.romeikat.datamessie.core.base.dao.impl.CrawlingDao.java

License:Open Source License

public List<CrawlingDto> getAsDtos(final SharedSessionContract ssc, final Long projectId) {
    // Query: Crawling
    final EntityWithIdQuery<Crawling> crawlingQuery = new EntityWithIdQuery<>(Crawling.class);
    crawlingQuery.addRestriction(Restrictions.eqOrIsNull("projectId", projectId));
    crawlingQuery.addOrder(Order.desc("started"));
    crawlingQuery.setResultTransformer(new AliasToBeanResultTransformer(CrawlingDto.class));

    // Done/*from  w ww.j a va2 s  .c  o m*/
    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("id"), "id");
    projectionList.add(Projections.property("started"), "started");
    projectionList.add(Projections.property("completed"), "completed");
    @SuppressWarnings("unchecked")
    final List<CrawlingDto> dtos = (List<CrawlingDto>) crawlingQuery.listForProjection(ssc, projectionList);

    // Set duration
    setDurationForDtos(dtos);

    return dtos;
}

From source file:com.romeikat.datamessie.core.base.dao.impl.CrawlingDao.java

License:Open Source License

public List<CrawlingOverviewDto> getAsOverviewDtos(final SharedSessionContract ssc, final Long projectId,
        final Long first, final Long count) {
    // Query: Crawling
    final EntityWithIdQuery<Crawling> crawlingQuery = new EntityWithIdQuery<>(Crawling.class);
    crawlingQuery.addRestriction(Restrictions.eqOrIsNull("projectId", projectId));
    crawlingQuery.setFirstResult(first == null ? null : first.intValue());
    crawlingQuery.setMaxResults(count == null ? null : count.intValue());
    crawlingQuery.addOrder(Order.desc("started"));
    crawlingQuery.setResultTransformer(new AliasToBeanResultTransformer(CrawlingOverviewDto.class));

    // Done/*from  w w  w .j  a v  a2 s  .  c  om*/
    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("id"), "id");
    projectionList.add(Projections.property("started"), "started");
    projectionList.add(Projections.property("completed"), "completed");
    @SuppressWarnings("unchecked")
    final List<CrawlingOverviewDto> dtos = (List<CrawlingOverviewDto>) crawlingQuery.listForProjection(ssc,
            projectionList);

    // Set duration
    setDurationForOverviewDtos(dtos);

    return dtos;
}

From source file:com.romeikat.datamessie.core.base.dao.impl.ProjectDao.java

License:Open Source License

public List<ProjectDto> getAllAsDtos(final SharedSessionContract ssc, final Long userId) {
    // Restrict to user
    final Collection<Long> projectIdsForUser = getIdsForUser(ssc, userId);
    if (projectIdsForUser.isEmpty()) {
        return Collections.emptyList();
    }//w w  w  .  j  a  va  2  s.c o  m

    // Query: Project
    final EntityWithIdQuery<Project> projectQuery = new EntityWithIdQuery<>(Project.class);
    projectQuery.addIdRestriction(projectIdsForUser);
    projectQuery.addOrder(Order.asc("name"));
    projectQuery.setResultTransformer(new AliasToBeanResultTransformer(ProjectDto.class));

    // Done
    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("id"), "id");
    projectionList.add(Projections.property("name"), "name");
    projectionList.add(Projections.property("crawlingEnabled"), "crawlingEnabled");
    projectionList.add(Projections.property("crawlingInterval"), "crawlingInterval");
    projectionList.add(Projections.property("preprocessingEnabled"), "preprocessingEnabled");
    @SuppressWarnings("unchecked")
    final List<ProjectDto> dtos = (List<ProjectDto>) projectQuery.listForProjection(ssc, projectionList);
    return dtos;
}