Example usage for org.hibernate.criterion Projections projectionList

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

Introduction

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

Prototype

public static ProjectionList projectionList() 

Source Link

Document

Create a new projection list.

Usage

From source file:com.nec.harvest.service.impl.OrganizationServiceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override//from   w  w w.  j a v  a 2 s  .co m
@SuppressWarnings("unchecked")
public List<OrganizationPaginationBean> findByStrCodeUp(String strCodeUp) throws ServiceException {
    if (StringUtils.isEmpty(strCodeUp)) {
        throw new IllegalArgumentException("The organization's code must not be null or empty");
    }

    final Session session = HibernateSessionManager.getSession();
    Transaction tx = null;

    List<OrganizationPaginationBean> organizations = new ArrayList<OrganizationPaginationBean>();
    try {
        tx = session.beginTransaction();
        Criteria criteria = repository.getCriteria(session, Organization.class)
                .setProjection(Projections.projectionList().add(Projections.property("strCode").as("strCode"))
                        .add(Projections.property("strNameR").as("strNameR"))
                        .add(Projections.property("comName").as("comName")))
                .add(Restrictions.eq("strCodeUp", strCodeUp))
                .add(Restrictions.eq("delKbn", Constants.STATUS_ACTIVE)).addOrder(Order.asc("strCode"))
                .setResultTransformer(new AliasToBeanResultTransformer(OrganizationPaginationBean.class));
        organizations = criteria.list();
        // Release transaction
        tx.commit();
        if (CollectionUtils.isEmpty(organizations)) {
            throw new ObjectNotFoundException("Could not find any Organization with strCodeUp " + strCodeUp);
        }
    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw new ServiceException(
                "An exception occured while finding Organization list with strCodeUp " + strCodeUp, ex);
    } finally {
        HibernateSessionManager.closeSession(session);
    }
    return organizations;
}

From source file:com.opiframe.DAO.TeacherDAO.java

public static List<Object[]> getTeacherCourses(String name) {
    List<Object[]> lst = null;
    try {//  ww  w  .j  a  v  a2s .c om
        ProjectionList projList = Projections.projectionList();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Teachers.class, "teach");
        criteria.createCriteria("teach.courseses", "courseses");
        projList.add(Projections.property("courseses.courseName"));
        projList.add(Projections.property("courseses.courseId"));
        criteria.setProjection(projList);
        criteria.add(Restrictions.eq("teach.teacherName", name));
        lst = criteria.list();
        session.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return lst;
}

From source file:com.painiu.core.dao.hibernate.PhotoDAOHibernate.java

License:Open Source License

static Criteria buildPhotoCriteria(final Session session, User user, String[] tags, boolean taggedAll,
        String text, Relation relation, boolean count) {
    Criteria criteria = session.createCriteria(Photo.class);

    if (user != null) {
        criteria.add(Restrictions.eq("user", user));

        if (relation != null) {
            criteria.add(/*ww w . ja  va 2s  .c  om*/
                    Restrictions.sqlRestriction(" {alias}.privacy & ? > 0", relation, UserTypes.relation()));
        }
    } else {
        criteria.add(
                Restrictions.sqlRestriction(" {alias}.privacy & ? > 0", Relation.NONE, UserTypes.relation()));

        criteria.setFetchMode("user", FetchMode.JOIN);
    }

    //if (user == null && group == null) {
    if (user == null) {
        Disjunction disjState = Restrictions.disjunction();

        disjState.add(Restrictions.eq("state", Photo.State.USER_POPULAR));
        disjState.add(Restrictions.eq("state", Photo.State.USER_COMMENDATORY));
        disjState.add(Restrictions.eq("state", Photo.State.USER_SENIOR));

        criteria.add(disjState);
    }

    //if (album != null) {
    //   criteria.createAlias("albumPhotos", "ap");
    //   criteria.add( Restrictions.eq("ap.album", album) );
    //}

    //if (group != null) {
    //   criteria.createAlias("groupPhotos", "gp");
    //   criteria.add( Restrictions.eq("gp.group", group) );
    //}

    if ((tags != null && tags.length > 0) || text != null) {
        Criteria subCriteria = criteria.createCriteria("photoTags", "tags");

        if (tags != null && tags.length > 0) {
            if (taggedAll) {
                Conjunction conj = Restrictions.conjunction();
                for (int i = 0; i < tags.length; i++) {
                    conj.add(Restrictions.eq("tagName", tags[i]));
                }
                subCriteria.add(conj);
            } else {
                Disjunction disj = Restrictions.disjunction();
                for (int i = 0; i < tags.length; i++) {
                    disj.add(Restrictions.eq("tagName", tags[i]));
                }
                subCriteria.add(disj);
            }
        }

        if (text != null) {
            Disjunction disj = Restrictions.disjunction();

            disj.add(Restrictions.like("title", text, MatchMode.ANYWHERE));
            disj.add(Restrictions.like("description", text, MatchMode.ANYWHERE));
            disj.add(Restrictions.eq("tags.tagName", text));

            criteria.add(disj);
        }
    }

    // TODO order parameters
    if (!count) {
        /*if (album != null) {
           criteria.addOrder(Order.asc("ap.position"));
        } else*/
        /*if (group != null) {
           criteria.addOrder(Order.asc("gp.position"));
        } else {*/
        criteria.addOrder(Order.desc("timestamp"));
        //}
    }
    // distinct ?
    if ((tags != null && tags.length > 1) || text != null) {
        ProjectionList proj = Projections.projectionList();

        proj.add(Projections.property("id")).add(Projections.property("title"))
                .add(Projections.property("width")).add(Projections.property("height"))
                .add(Projections.property("address.host")).add(Projections.property("address.dir"))
                .add(Projections.property("address.filename")).add(Projections.property("address.secret"))
                .add(Projections.property("address.username")).add(Projections.property("address.fileKey"));

        if (user == null) {
            criteria.createAlias("user", "user");
            proj.add(Projections.property("user.id")).add(Projections.property("user.username"))
                    .add(Projections.property("user.nickname")).add(Projections.property("user.buddyIcon.host"))
                    .add(Projections.property("user.buddyIcon.dir"))
                    .add(Projections.property("user.buddyIcon.filename"))
                    .add(Projections.property("user.buddyIcon.username"))
                    .add(Projections.property("user.buddyIcon.fileKey"));
        }

        criteria.setProjection(Projections.distinct(proj));

        criteria.setResultTransformer(new PhotoBeanResultTransformer());
    }

    return criteria;
}

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);/*  w  ww  . j a  v  a  2s.c  om*/
            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.internal.search.SearchProjectonListImpl.java

License:Open Source License

public SearchProjectonListImpl() {
    projections = Projections.projectionList();
}

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

License:Open Source License

private void processGroups() {
    if (groups.size() > 0) {
        if (projections == null) {
            projections = Projections.projectionList();
        }/*from  w w w .  j  av a  2s .com*/
        for (String group : groups) {
            projections.add(Projections.groupProperty(group));
            expectedFields.add(group);
            if (hasJoin) {
                for (Join join : joins) {
                    join.addExpectedField(group);
                }
            }
        }
    }
}

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

License:Open Source License

private void processAggregates() {
    if (aggregates.size() > 0) {
        if (projections == null) {
            projections = Projections.projectionList();
        }//www  .  j a v a 2 s .c  o  m
        for (String prop : aggregates.keySet()) {
            projections.add(aggregates.get(prop));
            expectedFields.add(prop);
        }
    }
}

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();
        }/*from w  w  w.j a v a  2  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  ww  .  ja v a 2s  . 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>();
    }/*  w w w .  j  a v  a2 s. 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;
}