Example usage for org.hibernate Criteria setProjection

List of usage examples for org.hibernate Criteria setProjection

Introduction

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

Prototype

public Criteria setProjection(Projection projection);

Source Link

Document

Used to specify that the query results will be a projection (scalar in nature).

Usage

From source file:ca.myewb.controllers.common.EventList.java

License:Open Source License

private List<EventModel> getUniqueEventList(Criteria criteria) {
    criteria.setProjection(Projections.groupProperty("id"));

    Iterator it = criteria.list().iterator();

    List<EventModel> list = new ArrayList<EventModel>();

    while (it.hasNext()) {
        list.add((EventModel) hibernateSession.load(EventModel.class, (Integer) it.next()));
    }/*from www  . j a v a 2  s. c  om*/

    return list;
}

From source file:ca.myewb.controllers.common.EventList.java

License:Open Source License

private int getUniqueEventCount(Criteria criteria) {
    criteria.setProjection(Projections.groupProperty("id"));
    return criteria.list().size();
}

From source file:ca.myewb.controllers.common.Member.java

License:Open Source License

private void searchMode(Context ctx) throws Exception, RedirectionException {
    MemberSearchForm searchForm = null;//from w  w w. j  a v  a2 s.  c  o  m
    List result = null;

    if (currentUser.isAdmin()) {
        result = hibernateSession.createQuery("FROM GroupChapterModel where visible=true").list();
    }

    // run search, store results in temp list
    if (requestParams.get("Advanced") != null) {
        searchForm = new MemberSearchForm(getInterpageVar("membersearchtarget") + "/search", requestParams,
                true, result);
        ctx.put("advanced", new Boolean(true));
    } else {
        searchForm = new MemberSearchForm(getInterpageVar("membersearchtarget") + "/search", requestParams,
                false, result);
    }

    Message m = searchForm.validate();

    if (m != null) // validation failed, redirect to self, next time we'll be entering the next block
    {
        // Display error and prompt user to fix
        throw getValidationException(searchForm, m, (String) getInterpageVar("membersearchtarget"));
    }

    //form validation succeeded!
    String first = searchForm.getParameter("Firstname");
    String last = searchForm.getParameter("Lastname");
    String email = searchForm.getParameter("Email");
    String city = searchForm.getParameter("City", false);
    String province = searchForm.getParameter("Province", false);
    String lang = searchForm.getParameter("Language", false);
    String gender = searchForm.getParameter("Gender", false);
    String birth = searchForm.getParameter("Birth", false);
    String student = searchForm.getParameter("Student", false);
    String username = searchForm.getParameter("Username", false);

    Criteria crit = hibernateSession.createCriteria(UserModel.class);

    if ((username != null) && !username.equals("")) {
        crit.add(Restrictions.like("username", "%" + username.trim() + "%"));
    }

    if ((first != null) && !first.equals("")) {
        crit.add(Restrictions.like("firstname", "%" + first.trim() + "%"));
    }

    if ((last != null) && !last.equals("")) {
        crit.add(Restrictions.like("lastname", "%" + last.trim() + "%"));
    }

    if ((email != null) && !email.equals("")) {
        List ids = HibernateUtil.currentSession()
                .createSQLQuery("SELECT userid FROM useremails e WHERE e.email LIKE '%" + email.trim() + "%'")
                .list();
        if (!ids.isEmpty()) {
            crit.add(Restrictions.in("id", ids));
        } else {
            crit.add(Restrictions.eq("email", "###invalidemail###")); //so that no results are given
        }
    }

    if ((city != null) && !city.equals("")) {
        crit.add(Restrictions.like("address", "%\n%" + city.trim() + "%\n%"));
    }

    if ((province != null) && !province.equals("")) {
        crit.add(Restrictions.like("address", "%\n%" + province.trim() + "%\n%"));
    }

    if ((lang != null) && !lang.equals("")) {
        crit.add(Restrictions.eq("language", lang.trim()));
    }

    if ((gender != null) && !gender.equals("")) {
        crit.add(Restrictions.eq("gender", gender.trim()));
    }

    if ((birth != null) && !birth.equals("")) {
        crit.add(Restrictions.eq("birth", new Integer(birth)));
    }

    if ((student != null) && !student.equals("")) {
        crit.add(Restrictions.eq("student", new Boolean(student)));
    }

    // Get "my" own lead groups, since I can only
    // see people in groups I lead
    crit.createAlias("roles", "r");
    crit.add(Restrictions.isNull("r.end"));

    if (!currentUser.isAdmin()) {
        crit.add(Restrictions.in("r.group", currentUser.getGroups('l')));
    } else {
        GroupChapterModel chapter = null;

        if (searchForm.getParameter("Chapter", false) != null) {
            if (!searchForm.getParameter("Chapter", false).equals("")) {
                chapter = (GroupChapterModel) hibernateSession.get(GroupChapterModel.class,
                        new Integer(searchForm.getParameter("Chapter", false)));
            }
        }

        if (chapter != null) {
            crit.add(Restrictions.eq("r.group", chapter));
            crit.add(Restrictions.eq("r.level", new Character('m')));
        }

        //don't filter out deleted users!
    }

    crit.add(Restrictions.ne("id", new Integer(1)));

    crit.addOrder(Order.asc("lastname"));
    crit.addOrder(Order.asc("firstname"));
    crit.setProjection(Projections.groupProperty("id"));
    crit.setMaxResults(101);

    List uniqueResultsList = crit.list();
    Vector<UserModel> uniqueResults = new Vector<UserModel>();

    if (uniqueResultsList.size() < 101) {
        Iterator iter = uniqueResultsList.iterator();

        while (iter.hasNext()) {
            Integer i = (Integer) iter.next();

            // This try/catch block is a workaround to the deleted-admin-causes-cgilib-blowup bug
            try {
                uniqueResults.add((UserModel) hibernateSession.get(UserModel.class, i));
            } catch (Exception e) {
                log.warn("Unable to add user to usersearch: id " + i.toString());
            }
        }
    } else {
        ctx.put("tooMany", "yes");
    }

    setInterpageVar("membersearchtempresults", uniqueResultsList);
    ctx.put("tempresults", uniqueResults); //NOT the ids, but the users
    ctx.put("searchmode", "yes");
    if (searchForm == null) {
        log.info("search form was null!");
        throw new RedirectionException(getInterpageVar("membersearchtarget") + "/new");
    }

    ctx.put("form", searchForm);
    ctx.put("target", getInterpageVar("membersearchtarget"));
}

From source file:ca.myewb.controllers.common.PostList.java

License:Open Source License

private int getUniquePostCount(Criteria criteria) {
    criteria.setProjection(Projections.groupProperty("id"));
    return criteria.list().size();
}

From source file:ca.myewb.controllers.common.PostList.java

License:Open Source License

private List<PostModel> getUniquePostList(Criteria criteria) {
    criteria.setProjection(Projections.groupProperty("id"));

    Iterator it = criteria.list().iterator();

    List<PostModel> list = new ArrayList<PostModel>();

    while (it.hasNext()) {
        list.add((PostModel) hibernateSession.load(PostModel.class, (Integer) it.next()));
    }/*  www .  ja v  a 2s .co  m*/

    return list;
}

From source file:ca.myewb.controllers.common.WhiteboardList.java

License:Open Source License

private List<WhiteboardModel> getUniqueWhiteboardList(Criteria criteria) {
    criteria.setProjection(Projections.groupProperty("id"));

    Iterator it = criteria.list().iterator();

    List<WhiteboardModel> list = new ArrayList<WhiteboardModel>();

    while (it.hasNext()) {
        list.add((WhiteboardModel) hibernateSession.load(WhiteboardModel.class, (Integer) it.next()));
    }/*from   w  w w  .j a v a2  s  .  c o  m*/

    return list;
}

From source file:ca.myewb.controllers.common.WhiteboardList.java

License:Open Source License

private int getUniqueWhiteboardCount(Criteria criteria) {
    criteria.setProjection(Projections.groupProperty("id"));
    return criteria.list().size();
}

From source file:ca.myewb.controllers.mailing.ListMember.java

License:Open Source License

private List<GroupModel> getControllableGroups() {
    List<GroupModel> lists;

    if (currentUser.isAdmin()) {
        lists = (new SafeHibList<GroupModel>(hibernateSession
                .createQuery("SELECT g FROM GroupModel g where g.visible=true and g.admin=false"))).list();
    } else {/*from  w  w  w. ja  v  a  2 s  .  c  o m*/
        Criteria crit = hibernateSession.createCriteria(GroupModel.class);

        crit.createAlias("roles", "r");
        crit.add(Restrictions.eq("r.user", currentUser));
        crit.add(Restrictions.isNull("r.end"));
        crit.add(Restrictions.eq("r.level", new Character('l')));
        crit.add(Restrictions.eq("visible", new Boolean(true)));
        crit.add(Restrictions.eq("admin", new Boolean(false)));

        crit.setProjection(Projections.groupProperty("id"));
        lists = (new SafeHibList<GroupModel>(crit)).list();

        Iterator it = lists.iterator();
        List<GroupModel> lists2 = new ArrayList<GroupModel>();

        while (it.hasNext()) {
            lists2.add((GroupModel) hibernateSession.get(GroupModel.class, (Integer) it.next()));
        }

        lists = lists2;
        lists.addAll(currentUser.getChapter().getVisibleChildren());
    }

    return lists;
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<UserDetail> getAllUserDetail(PagingLoadConfig config) throws PigeException {

    PermissionHelper.checkUserManagementPermission(getThreadLocalRequest());

    logger.debug("Rcupration des dtails de tous les usagers " + "[Pagination: dpart=" + config.getOffset()
            + ", max=" + config.getLimit() + "] ...");

    BaseFilterPagingLoadConfig xConfig = null;
    if (config instanceof BaseFilterPagingLoadConfig) {
        xConfig = (BaseFilterPagingLoadConfig) config;
    }/*from  w  w  w. ja  v  a 2  s . c o m*/

    Session session = null;
    Transaction tx = null;
    List<User> users = null;
    List<UserDetail> userDetailList = null;
    Integer userCount = 0;
    Integer start;
    Integer limit;

    try {

        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(User.class);
        Criterion filterCriterion = PigeHibernateUtil.buildFilterCriterion(xConfig.getFilterConfigs());
        if (filterCriterion != null) {
            criteria.add(filterCriterion);
        }

        userCount = (Integer) session.createCriteria(User.class).setProjection(Projections.rowCount())
                .uniqueResult();

        start = config.getOffset();
        limit = userCount;
        if (limit > 0 && config.getLimit() > 0) {
            limit = Math.min(config.getLimit(), limit);
        }

        logger.debug("Paramtres d'extraction des donnes: dpart=" + start + ", max=" + limit + "] ...");

        criteria.setProjection(null);
        criteria.setResultTransformer(Criteria.ROOT_ENTITY);

        users = (List) criteria.setFirstResult(start).setMaxResults(limit).list();

        tx.commit();

        userDetailList = new ArrayList();
        for (User u : users) {
            userDetailList.add(u.getUserDetail());
        }

        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return new BasePagingLoadResult(userDetailList, config.getOffset(), userCount);
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<Loan> getLoans(PagingLoadConfig configs) throws PigeException {

    PermissionHelper.checkLoanManagementPermission(getThreadLocalRequest());

    logger.debug("Rcupration des emprunts " + "[Pagination: dpart=" + configs.getOffset() + ", max="
            + configs.getLimit() + "] ...");

    Transaction tx = null;/*from  ww  w  .j a  v  a2s .co m*/
    List<Loan> loans = null;
    Session session = null;
    Integer loanCount = 0;
    Integer offset = 0;
    Integer limit = 0;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Date startDate = null;
        Date endDate = null;

        Criteria loansCriteria = session.createCriteria(Loan.class);
        Criteria usersCriteria = null;

        List<FilterConfig> searchConfigs = configs.get(PIGE.SEARCH_CONFIGS);
        List<FilterConfig> filterConfigs = configs.get(PIGE.FILTER_CONFIGS);

        List<FilterConfig> userParam = null;
        List<FilterConfig> loanParam = null;

        if (searchConfigs != null) {
            for (FilterConfig fc : searchConfigs) {
                if (fc.getField().equals("params")) {
                    logger.debug("Extraction du FilterConfig 'params'...");
                    BaseListFilterConfig blfc = (BaseListFilterConfig) fc;
                    userParam = blfc.get(PIGE.USER_CONFIGS);
                    logger.debug("Extraction de la liste 'user-param'..." + (userParam == null ? "N/D" : "OK"));
                    loanParam = blfc.get(PIGE.LOAN_CONFIGS);
                    logger.debug("Extraction de la liste 'loan-param'..." + (loanParam == null ? "N/D" : "OK"));
                    break;
                }
            }
        }

        Criterion filterCriterion = null;
        Iterator<FilterConfig> itr = null;
        FilterConfig fc = null;

        if (loanParam != null) {
            itr = loanParam.iterator();
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc instanceof BaseDateFilterConfig) {
                    BaseDateFilterConfig dateFC = (BaseDateFilterConfig) fc;
                    startDate = dateFC.get(PIGE.START_DATE, null);
                    endDate = dateFC.get(PIGE.END_DATE, null);
                    itr.remove();
                    break;
                }
            }

            FilterConfig matchModeConfig = new BaseBooleanFilterConfig();
            matchModeConfig.setField(PIGE.MATCH_MODE);
            matchModeConfig.setValue(Boolean.FALSE);
            loanParam.add(matchModeConfig);
            filterCriterion = PigeHibernateUtil.buildFilterCriterion(loanParam);
            if (filterCriterion != null) {
                loansCriteria.add(filterCriterion);
            }

            if (startDate != null) {
                logger.debug("Restrictions sur la date d'chance: entre " + startDate.toString() + " et "
                        + (endDate == null ? new Date() : endDate) + " inclusivement...");
                loansCriteria.add(Restrictions.between(Loan.START_DATE_REF, startDate,
                        (endDate == null ? new Date() : endDate)));
            } else if (endDate != null) {
                logger.debug("Restrictions sur la date d'chance: <= " + endDate.toString());
                loansCriteria.add(Restrictions.le(Loan.START_DATE_REF, endDate));
            }
        }

        if (filterConfigs != null && filterConfigs.size() > 0) {
            filterCriterion = PigeHibernateUtil.buildFilterCriterion(filterConfigs);
            if (filterCriterion != null) {
                loansCriteria.add(filterCriterion);
            }
        }

        usersCriteria = loansCriteria.createCriteria(Loan.USER_REF, "usr", Criteria.LEFT_JOIN);

        if (userParam != null) {
            String userScope = null;
            itr = userParam.iterator();
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc.getField().equals("scope")) {
                    userScope = (String) fc.getValue();
                    itr.remove();
                    break;
                }
            }
            if (userScope != null && !userScope.isEmpty() && !userScope.equals("*")) {
                logger.debug(
                        "Restriction de la recherche sur un usager " + "spcifique: [" + userScope + "] ...");
                usersCriteria.add(Restrictions.like(User.IDENTIFIER_REF, userScope, MatchMode.EXACT));
            } else {
                logger.debug("Restriction de la recherche sur un ou des " + "usager spcifique...");
                filterCriterion = PigeHibernateUtil.buildFilterCriterion(userParam);
                if (filterCriterion != null) {
                    usersCriteria.add(filterCriterion);
                }
            }
        }

        loanCount = (Integer) loansCriteria.setProjection(Projections.rowCount()).uniqueResult();

        offset = configs.getOffset();
        limit = loanCount;
        if (limit > 0 && configs.getLimit() > 0) {
            limit = Math.min(configs.getLimit(), limit);
        }

        logger.debug("Paramtres d'extraction des donnes: dpart=" + offset + ", max=" + limit + "] ...");

        loansCriteria.setProjection(null);
        loansCriteria.setResultTransformer(Criteria.ROOT_ENTITY);

        loans = (List) loansCriteria.addOrder(Order.asc("usr." + User.LOAN_NO_REF)).setFirstResult(offset)
                .setMaxResults(limit).list();

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (loans == null) {
        loans = new ArrayList();
    }

    return new BasePagingLoadResult(loans, offset, loanCount);
}