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:com.bookselling.dao.SellingPostDaoImpl.java

@Override
public PaginationData<SellingPost> getBestSelling(int first, int items) {
    SQLQuery sqlQuery = getSession().createSQLQuery("select boughtEntityId, sum(quatity) "
            + "from tradedetail trd " + "group by boughtEntityId " + "order by sum(quatity) desc");
    sqlQuery.setFirstResult(first).setMaxResults(items);

    List result = sqlQuery.list();
    Integer boughtEntityIds[] = new Integer[result.size()];
    int index = 0;
    for (Object rows : boughtEntityIds) {
        Object[] row = (Object[]) rows;
        boughtEntityIds[index++] = Integer.valueOf((String) row[0]);
    }//from   ww  w.  j  ava2  s . co  m

    Criteria criteria = getSession().createCriteria(SellingPost.class);
    criteria.add(Restrictions.eq("status", SellingPostStatus.CONFIRM))
            .add(Restrictions.in("id", boughtEntityIds));

    Set<SellingPost> posts = new HashSet<>(criteria.list());
    HibernateInitSupport.setCls(SellingPost.class);
    for (SellingPost post : posts)
        HibernateInitSupport.initDomain(post);

    PaginationData paginationData = new PaginationData(
            (long) criteria.setProjection(Projections.rowCount()).uniqueResult(), items, first, posts);

    return paginationData;
}

From source file:com.bookselling.dao.SellingPostDaoImpl.java

@Override
public PaginationData<SellingPost> getBySubject(int first, int items, Subject subject) {
    Integer subjectId = subject.getId();
    Criteria criteria = getSession().createCriteria(SellingPost.class);
    criteria.createAlias("purchasingSellingEntity", "slen").createAlias("slen.subjects", "sbj")
            .add(Restrictions.eq("status", SellingPostStatus.CONFIRM))
            .add(Restrictions.eq("sbj.id", subjectId));

    //Ly s dng/*w  w w.j  av  a  2  s  .  co  m*/
    long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult();

    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .setProjection(Projections.distinct(Projections.id())).addOrder(Order.desc("id"))
            .setFirstResult(first).setMaxResults(items);

    List<Integer> ids = new ArrayList<>();
    for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();)
        ids.add(temp.next());

    //Criteria ph
    Criteria subCriteria = getSession().createCriteria(SellingPost.class);
    subCriteria.createAlias("purchasingSellingEntity", "bk").createAlias("bk.subjects", "sbj")
            .createAlias("bk.publisher", "pub").createAlias("seller", "sl").createAlias("sl.account", "acc")
            .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1))).addOrder(Order.desc("id"));

    Set<SellingPost> posts = new HashSet<>(subCriteria.list());
    HibernateInitSupport.setCls(SellingPost.class);
    for (SellingPost post : posts)
        HibernateInitSupport.initDomain(post);

    PaginationData paginationData = new PaginationData(rowCount, items, first, posts);

    return paginationData;
}

From source file:com.bookselling.dao.SubjectDaoImpl.java

@Override
public PaginationData filter(SubjectFilterForm form, int first, int items) {
    Criteria criteria = getSession().createCriteria(Subject.class);

    //Get keyword
    String keyword = "%" + form.getKeyword() + "%";

    //Set up criteria
    criteria.add(Restrictions.like("name", keyword));

    //Get list//  w w w  . jav  a2  s  .c o m
    Set<Subject> subjects = new LinkedHashSet<>(criteria.list());

    //pagination
    PaginationData paginationData = new PaginationData(
            (long) criteria.setProjection(Projections.rowCount()).uniqueResult(), items, first, subjects);

    return paginationData;
}

From source file:com.bookselling.dao.SystemInvoiceDaoImpl.java

@Override
public PaginationData<SystemInvoice> filter(SystemInvoiceFilterForm form, int first, int items) {
    String keyword = form.getKeyword();
    SystemInvoiceFilterType searchBy = form.getSearchBy();
    Date fromDate = form.getFromDate();
    Date toDate = form.getToDate();
    SystemInvoiceOrderType orderBy = form.getOrderBy();
    SortType sortType = form.getSortType();

    Criteria criteria = getSession().createCriteria(SystemInvoice.class);
    criteria.createAlias("poster", "pst").createAlias("post", "ps").createAlias("pst.account", "acc");

    if (keyword == null) {
        keyword = "%" + keyword + "%";
        if (searchBy == SystemInvoiceFilterType.ACCOUNT)
            criteria.add(Restrictions.like("acc.username", keyword));
        else if (searchBy == SystemInvoiceFilterType.POSTER) {
            Name name = new Name();
            name.setName(keyword);//from   w  w w . j  av a2 s  .  co  m
            criteria.add(Restrictions.like("pst.name", name));
        } else if (searchBy == SystemInvoiceFilterType.POST_HEADER)
            criteria.add(Restrictions.like("ps.header", keyword));
    }

    if (fromDate != null)
        criteria.add(Restrictions.ge("createdDate", fromDate));
    if (toDate != null)
        criteria.add(Restrictions.le("createdDate", toDate));

    String propertyName = null;
    if (orderBy == SystemInvoiceOrderType.ACCOUNT)
        propertyName = "acc.username";
    else if (orderBy == SystemInvoiceOrderType.POSTER)
        propertyName = "pst.name";
    else if (orderBy == SystemInvoiceOrderType.POST_HEADER)
        propertyName = "ps.header";
    else if (orderBy == SystemInvoiceOrderType.DATE)
        propertyName = "createdDate";

    //Ly s dng
    long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult();

    //Ly id
    criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items)
            .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

    List<Integer> ids = new ArrayList<>();
    for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();)
        ids.add(temp.next());

    //Criteria ph
    Criteria subCriteria = getSession().createCriteria(SystemInvoice.class);
    subCriteria.createAlias("poster", "pst").createAlias("post", "ps").createAlias("pst.account", "acc")
            .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1)))
            .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

    Set<SystemInvoice> invoices = new LinkedHashSet<>(subCriteria.list());
    HibernateInitSupport.setCls(SystemInvoice.class);
    for (SystemInvoice invoice : invoices)
        HibernateInitSupport.initDomain(invoice);

    PaginationData paginationData = new PaginationData(rowCount, items, first, invoices);

    return paginationData;
}

From source file:com.bookselling.dao.TradeDaoImpl.java

@Override
public PaginationData<Trade> get(User user, int first, int items) {
    Criteria criteria = getSession().createCriteria(Trade.class);
    criteria.createAlias("buyer", "byer").add(Restrictions.eq("byer.id", user.getId()));

    criteria.setFirstResult(first);/*from  www  .j  a va 2  s . c o  m*/
    criteria.setMaxResults(items);

    Set<Trade> trades = new HashSet<>(criteria.list());
    HibernateInitSupport.setCls(Trade.class);
    for (Trade trade : trades)
        HibernateInitSupport.initDomain(trade);

    PaginationData paginationData = new PaginationData(
            (long) criteria.setProjection(Projections.rowCount()).uniqueResult(), items, first, trades);

    return paginationData;
}

From source file:com.bookselling.dao.TradeDaoImpl.java

private Object[] filterCriteria(TradeFilterForm form, int first, int items, int id) {
    String keyword = form.getKeyword();
    TradeFilterType searchBy = form.getSearchBy();
    Date fromDate = form.getFromDate();
    Date toDate = form.getToDate();
    Double fromPrice = form.getFromPrice();
    Double toPrice = form.getToPrice();
    TradeOrderType orderBy = form.getOrderBy();
    SortType sortType = form.getSortType();

    Criteria criteria = getSession().createCriteria(Trade.class);
    criteria.createAlias("buyer", "bye").createAlias("bye.account", "acc");

    if (keyword != null) {
        keyword = "%" + keyword + "%";
        if (searchBy == TradeFilterType.ADDRESS) {
            Address address = new Address();
            address.setAddress(keyword);
            criteria.add(Restrictions.like("contact.address", address));
        } else if (searchBy == TradeFilterType.PHONE) {
            PhoneNumber phone = new PhoneNumber();
            phone.setPhoneNumber(keyword);
            criteria.add(Restrictions.like("contact.phoneNumber", phone));
        }/*w  w  w  .  j  a v  a 2  s.  c  o m*/
    }

    if (fromDate != null)
        criteria.add(Restrictions.ge("createdDate", fromDate));
    if (toDate != null)
        criteria.add(Restrictions.le("createdDate", toDate));

    if (fromPrice != null)
        criteria.add(Restrictions.ge("totalPrice", fromPrice));
    if (toPrice != null)
        criteria.add(Restrictions.le("totalPrice", toPrice));

    String propertyName = null;
    if (orderBy == TradeOrderType.BUYER)
        propertyName = "acc.username";
    else if (orderBy == TradeOrderType.OWNER)
        propertyName = "bye.name";
    else if (orderBy == TradeOrderType.DATE)
        propertyName = "createdDate";
    else if (orderBy == TradeOrderType.PRICE)
        propertyName = "totalPrice";

    if (id != -1)
        criteria.add(Restrictions.eq("bye.id", id));

    //Ly s dng
    long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult();

    //Ly id
    criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items)
            .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

    List<Integer> ids = new ArrayList<>();
    for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();)
        ids.add(temp.next());

    //Criteria ph
    Criteria subCriteria = getSession().createCriteria(Trade.class);
    subCriteria.createAlias("buyer", "bye").createAlias("bye.account", "acc")
            .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1)))
            .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

    return new Object[] { subCriteria, rowCount };
}

From source file:com.bookselling.dao.UserDaoImpl.java

@Override
public PaginationData get(int first, int items) {
    Criteria criteria = getSession().createCriteria(User.class);
    criteria.createAlias("account", "acc").createAlias("acc.role", "rl").add(Restrictions.eq("rl.id", USER_ID));

    Set<User> users = new HashSet<>(criteria.list());
    HibernateInitSupport.setCls(User.class);
    for (User user : users)
        HibernateInitSupport.initDomain(user);

    //Pagination// w  ww  .  ja va2 s  . c  om
    PaginationData paginationData = new PaginationData(
            (long) criteria.setProjection(Projections.rowCount()).uniqueResult(), items, first, users);

    return paginationData;
}

From source file:com.bookselling.dao.UserDaoImpl.java

@Override
public PaginationData filter(UserFilterForm form, int first, int items) {
    Criteria criteria = getSession().createCriteria(User.class);

    //Get form data
    String keyword = form.getKeyword();
    AccountStatus[] accStatus = form.getAccStatus();
    UserFilterType searchBy = form.getSearchBy();
    Date fromDate = form.getFromDate();
    Date toDate = form.getToDate();
    UserOrderType orderBy = form.getOrderBy();
    SortType sortType = form.getSortType();

    //To criteria
    criteria.createAlias("account", "acc").createAlias("acc.role", "rls").add(Restrictions.eq("rls.id", 1));

    if (keyword != null && !keyword.isEmpty()) {
        keyword = "%" + keyword + "%";
        if (searchBy == UserFilterType.ADDRESS) {
            Address address = new Address();
            address.setAddress(keyword);
            criteria.add(Restrictions.like("contact.address", address));
        } else if (searchBy == UserFilterType.EMAIL) {
            criteria.add(Restrictions.like("acc.email", keyword));
        } else if (searchBy == UserFilterType.OWNER) {
            Name name = new Name();
            name.setName(keyword);/*  www  .ja  v a 2 s . co  m*/
            criteria.add(Restrictions.like("name", name));
        } else if (searchBy == UserFilterType.PHONE) {
            PhoneNumber phone = new PhoneNumber();
            phone.setPhoneNumber(keyword);
            criteria.add(Restrictions.like("contact.phone", phone));
        } else if (searchBy == UserFilterType.USERNAME) {
            criteria.add(Restrictions.like("acc.username", keyword));
        }
    }

    if (accStatus.length != 0) {
        criteria.add(Restrictions.in("acc.status", accStatus));
    }

    if (fromDate != null)
        criteria.add(Restrictions.ge("acc.createdDate", fromDate));
    if (toDate != null)
        criteria.add(Restrictions.le("acc.createdDate", toDate));

    String propertyName = null;
    if (orderBy == UserOrderType.CREATEDDATE)
        propertyName = "acc.createdDate";
    else if (orderBy == UserOrderType.NAME)
        propertyName = "name";
    else if (orderBy == UserOrderType.STATUS)
        propertyName = "acc.status";
    else if (orderBy == UserOrderType.USERNAME)
        propertyName = "acc.username";

    //Ly s dng
    long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult();

    //Ly id
    criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items)
            .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

    List<Integer> ids = new ArrayList<>();
    for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();)
        ids.add(temp.next());

    //Criteria ph
    Criteria subCriteria = getSession().createCriteria(User.class);
    subCriteria.createAlias("account", "acc").createAlias("acc.role", "rls").add(Restrictions.eq("rls.id", 1))
            .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1)))
            .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

    //get list
    Set<User> users = new LinkedHashSet<>(subCriteria.list());
    for (User user : users) {
        HibernateInitSupport.initUser(user);
    }

    //Pagination
    PaginationData paginationData = new PaginationData(rowCount, items, first, users);

    return paginationData;
}

From source file:com.cai310.lottery.service.lottery.keno.impl.KenoServiceImpl.java

@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public BigDecimal countSubscribedCost(Long schemeId, final Long userId) {
    final S scheme = getScheme(schemeId);
    return (BigDecimal) subscriptionDao.execute(new CriteriaExecuteCallBack() {
        public Object execute(Criteria criteria) {
            criteria.setProjection(Projections.sum("cost"));
            criteria.add(Restrictions.eq("schemeId", scheme.getId()));
            criteria.add(Restrictions.eq("userId", userId));
            criteria.add(Restrictions.eq("state", SubscriptionState.NORMAL));
            criteria.add(Restrictions.eq("lotteryType", scheme.getLotteryType()));
            return criteria.uniqueResult();
        }/* w  ww .j  a v a2  s. com*/
    });
}

From source file:com.certus.actions.AdimnProductFilterAction.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Session ses = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    int pageIndex = 0;
    int totalNumberOfRecords = 0;
    int numberOfRecordsPerPage = 9;

    String sPageIndex = request.getParameter("pgIndex");
    pageIndex = sPageIndex == null ? 1 : Integer.parseInt(sPageIndex);

    int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;

    if (request.getParameter("category") != null) {
        List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class, "phs")
                .createAlias("phs.size", "size").createAlias("phs.product", "pro")
                .createAlias("pro.subCategory", "sub").createAlias("sub.category", "cat")
                .add(Restrictions.eq("size.sizeName", request.getParameter("size")))
                .add(Restrictions.eq("sub.subCategoryName", request.getParameter("sub_category")))
                .add(Restrictions.eq("cat.catName", request.getParameter("category")))
                .add(Restrictions.eq("pro.availability", Boolean.valueOf(request.getParameter("status"))))
                .setFirstResult(s).setMaxResults(numberOfRecordsPerPage).list();
        String s1 = "", s2 = "";
        for (ProductHasSize pro : phs) {
            String avlOn = pro.getProduct().isAvailability() ? "btn-danger" : "btn-default";
            String avlOff = pro.getProduct().isAvailability() ? "btn-default" : "btn-danger";
            s1 = s1 + "<tr>" + "<td>" + pro.getProduct().getName() + "</td>" + "<td>"
                    + "<div class='btn-group btn-toggle'>" + "<button class='btn btn-xs " + avlOn
                    + "' onclick='onBtnClick(" + pro.getProduct().getId() + "," + pageIndex
                    + ");' type='button'>ON</button>" + "<button class='btn btn-xs " + avlOff
                    + "' onclick='offBtnClick(" + pro.getProduct().getId() + "," + pageIndex
                    + ");' type='button'>OFF</button>" + "</div>" + "</td>" + "<td>"
                    + pro.getSize().getSizeName() + "</td>" + "<td>" + pro.getQnty() + "</td>" + "<td>Rs."
                    + pro.getPrice() + "</td>" + "<td>" + "<a href='edit_product.jsp?pid="
                    + pro.getProduct().getId() + "&sid=" + pro.getSize().getId() + "'>"
                    + "    <span class='glyphicon glyphicon-edit'></span>" + "</a>" + "</td>" + "</tr>"
                    + "<tr> ";

        }//w  w  w  . j av  a 2s .c om
        Criteria criteriaCount = ses.createCriteria(ProductHasSize.class, "phs").createAlias("phs.size", "size")
                .createAlias("phs.product", "pro").createAlias("pro.subCategory", "sub")
                .createAlias("sub.category", "cat")
                .add(Restrictions.eq("size.sizeName", request.getParameter("size")))
                .add(Restrictions.eq("sub.subCategoryName", request.getParameter("sub_category")))
                .add(Restrictions.eq("cat.catName", request.getParameter("category")))
                .add(Restrictions.eq("pro.availability", Boolean.valueOf(request.getParameter("status"))));
        criteriaCount.setProjection(Projections.rowCount());
        totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();

        int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;

        if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
            noOfPages = noOfPages + 1;
        }

        for (int j = 1; j <= noOfPages; j++) {
            if (noOfPages > 1) {
                String myurl = "products.jsp?sizeName=" + request.getParameter("size") + "&" + "subCategory="
                        + request.getParameter("sub_category") + "&" + "catName="
                        + request.getParameter("category") + "&status=" + request.getParameter("status")
                        + "&pgIndex=" + j;
                if (j == pageIndex) {
                    s2 += "<span class='current'>" + j + "</span>";
                } else {
                    s2 += "<a href='" + myurl + "'>" + j + "</a>";
                }
            }

        }
        ses.close();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");

    } else {
        List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class).setFirstResult(s)
                .setMaxResults(numberOfRecordsPerPage).list();
        String s1 = "", s2 = "";
        for (ProductHasSize pro : phs) {
            String avlOn = pro.getProduct().isAvailability() ? "btn-danger" : "btn-default";
            String avlOff = pro.getProduct().isAvailability() ? "btn-default" : "btn-danger";
            s1 = s1 + "<tr>" + "<td>" + pro.getProduct().getName() + "</td>" + "<td>"
                    + "<div class='btn-group btn-toggle'>" + "<button class='btn btn-xs " + avlOn
                    + "' onclick='onBtnClick(" + pro.getProduct().getId() + "," + pageIndex
                    + ");' type='button'>ON</button>" + "<button class='btn btn-xs " + avlOff
                    + "' onclick='offBtnClick(" + pro.getProduct().getId() + "," + pageIndex
                    + ");' type='button'>OFF</button>" + "</div>" + "</td>" + "<td>"
                    + pro.getSize().getSizeName() + "</td>" + "<td>" + pro.getQnty() + "</td>" + "<td>Rs."
                    + pro.getPrice() + "</td>" + "<td>" + "<a href='edit_product.jsp?pid="
                    + pro.getProduct().getId() + "&sid=" + pro.getSize().getId() + "'>"
                    + "    <span class='glyphicon glyphicon-edit'></span>" + "</a>" + "</td>" + "</tr>"
                    + "<tr> ";

        }

        Criteria criteriaCount = ses.createCriteria(ProductHasSize.class);
        criteriaCount.setProjection(Projections.rowCount());
        totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();

        int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;

        if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
            noOfPages = noOfPages + 1;
        }

        for (int j = 1; j <= noOfPages; j++) {
            if (noOfPages > 1) {
                String myurl = "products.jsp?pgIndex=" + j;
                if (j == pageIndex) {
                    s2 += "<span class='current'>" + j + "</span>";
                } else {
                    s2 += "<a href='" + myurl + "'>" + j + "</a>";
                }

            }
        }
        ses.close();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");

    }
}