Example usage for org.hibernate.criterion Projections countDistinct

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

Introduction

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

Prototype

public static CountProjection countDistinct(String propertyName) 

Source Link

Document

A distinct property value count projection

Usage

From source file:ar.com.zauber.commons.repository.aggregate.ProjectionAggregateFunctionVisitor.java

License:Apache License

/** crea projecciones en base a {@link PropertyAggregateFunction}. */
private static Projection createPropertyProjection(final PropertyAggregateFunction paf) {
    final String propertyName = paf.getProperty();
    final Projection projection;

    if (paf instanceof AveragePropertyAggregateFunction) {
        projection = Projections.avg(propertyName);
    } else if (paf instanceof CountDistinctPropertyAggregateFunction) {
        projection = Projections.countDistinct(propertyName);
    } else if (paf instanceof CountPropertyAggregateFunction) {
        projection = Projections.count(propertyName);
    } else if (paf instanceof MaxPropertyAggregateFunction) {
        projection = Projections.max(propertyName);
    } else if (paf instanceof MinPropertyAggregateFunction) {
        projection = Projections.min(propertyName);
    } else if (paf instanceof SumPropertyAggregateFunction) {
        projection = Projections.sum(propertyName);
    } else if (paf instanceof GroupPropertyAggregateFilter) {
        projection = Projections.groupProperty(propertyName);
    } else {/*from w ww. j av a  2s  .  co  m*/
        throw new IllegalArgumentException("don't know how to process " + paf.getClass());
    }

    return projection;
}

From source file:au.org.theark.phenotypic.model.dao.PhenotypicDao.java

License:Open Source License

public long getCountOfCollectionsWithDataInStudy(Study study) {
    long count = 0;

    if (study.getId() != null) {
        Collection<PhenoDataSetCollection> phenoCollectionColn = getPhenoCollectionByStudy(study);

        for (Iterator iterator = phenoCollectionColn.iterator(); iterator.hasNext();) {
            PhenoDataSetCollection phenoCollection = (PhenoDataSetCollection) iterator.next();

            Criteria criteria = getSession().createCriteria(PhenoDataSetData.class);
            criteria.add(Restrictions.eq("phenCollection", phenoCollection));
            ProjectionList projList = Projections.projectionList();
            projList.add(Projections.countDistinct("collection"));
            criteria.setProjection(projList);
            List list = criteria.list();
            count = count + ((Long) list.get(0));
        }/*from  www.  j av  a 2  s  .  c  om*/
    }

    return count;
}

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

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

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

    if (keyword != null) {
        keyword = "%" + keyword + "%";
        if (searchBy == SellerInvoiceFilterType.BUYER)
            criteria.add(Restrictions.like("acc.username", keyword));
        else if (searchBy == SellerInvoiceFilterType.OWNER) {
            Name name = new Name();
            name.setName(keyword);/*from   w w w.ja  va2  s .  c o  m*/
            criteria.add(Restrictions.like("bye.name", name));
        } else if (searchBy == SellerInvoiceFilterType.ADDRESS) {
            Address address = new Address();
            address.setAddress(keyword);
            criteria.add(Restrictions.like("contact.address", address));
        } else if (searchBy == SellerInvoiceFilterType.PHONE) {
            PhoneNumber phone = new PhoneNumber();
            phone.setPhoneNumber(keyword);
            criteria.add(Restrictions.like("contact.phoneNumber", phone));
        }
    }

    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 == SellerInvoiceOrderType.BUYER)
        propertyName = "acc.username";
    else if (orderBy == SellerInvoiceOrderType.OWNER)
        propertyName = "bye.name";
    else if (orderBy == SellerInvoiceOrderType.DATE)
        propertyName = "createdDate";
    else if (orderBy == SellerInvoiceOrderType.PRICE)
        propertyName = "totalPrice";

    if (id != -1)
        criteria.add(Restrictions.eq("sl.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(SellerInvoice.class);
    subCriteria.createAlias("seller", "sl").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.SellingPostDaoImpl.java

private Object[] genericFilter(SellingPostFilterForm criteriaForm, int first, int items, int id) {
    Criteria criteria = getSession().createCriteria(SellingPost.class);

    //parse form//from   ww  w  .  j  a  v  a  2  s .co m
    SellingPostFilterForm form = criteriaForm;

    //get form data
    String keyword = form.getKeyword();
    Double minPrice = form.getMinPrice();
    Double maxPrice = form.getMaxPrice();
    QuatityFilterType quatityStatus = form.getQuatityStatus();
    SellingPostFilterType searchBy = form.getSearchBy();
    SellingPostStatus sellingPostStatus[] = form.getSellingPostStatus();
    Set<Subject> subjects = form.getSubjects();
    Integer subjectIds[] = new Integer[subjects.size()];
    Subject subjectsArray[] = subjects.toArray(new Subject[subjectIds.length]);
    for (int i = 0; i < subjects.size(); i++)
        subjectIds[i] = subjectsArray[i].getId();

    //create criteria
    criteria.createAlias("purchasingSellingEntity", "bk").createAlias("bk.subjects", "sbj")
            .createAlias("bk.publisher", "pub").createAlias("seller", "sl").createAlias("sl.account", "acc");

    //search by keyword
    if (keyword != null && !keyword.isEmpty()) {
        keyword = "%" + keyword.trim() + "%";
        if (searchBy == SellingPostFilterType.HEADER)
            criteria.add(Restrictions.like("header", keyword));
        else if (searchBy == SellingPostFilterType.NAME) {
            criteria.add(Restrictions.like("bk.name", keyword)); //product
        } else if (searchBy == SellingPostFilterType.PUBLISHER) {
            criteria.add(Restrictions.like("pub.name", keyword));
        }
    }

    //search with price range        
    criteria.add(Restrictions.between("bk.sellingPrice", minPrice == null ? 0 : minPrice,
            maxPrice == null ? Integer.MAX_VALUE : maxPrice));

    //search with quatity status
    if (quatityStatus == QuatityFilterType.AVAILABLE)
        criteria.add(Restrictions.gt("bk.quatity", 0));
    else if (quatityStatus == QuatityFilterType.OUTOFSTOCK)
        criteria.add(Restrictions.eq("bk.quatity", 0));

    //search with selling post status
    if (sellingPostStatus.length != 0)
        criteria.add(Restrictions.in("status", sellingPostStatus));

    //search with subjects
    if (subjectIds.length != 0)
        criteria.add(Restrictions.in("sbj.id", subjectIds));

    //get data from form
    SortType sortType = form.getSortType();
    SellingPostOrderType sortByProperty = form.getSortByProperty();

    //Set up criteria
    String propertyName = null;
    if (sortByProperty == SellingPostOrderType.HEADER)
        propertyName = "header";
    else if (sortByProperty == SellingPostOrderType.NAME)
        propertyName = "bk.name";
    else if (sortByProperty == SellingPostOrderType.PUBLISHER)
        propertyName = "pub.name";
    else if (sortByProperty == SellingPostOrderType.CREATEDDATE)
        propertyName = "createdDate";
    else if (sortByProperty == SellingPostOrderType.PRICE)
        propertyName = "bk.sellingPrice";

    if (id != -1)
        criteria.add(Restrictions.eq("sl.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(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(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName));

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

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

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

    criteria.setFirstResult(first);//from w w w  . j a  v a  2  s .  c  o  m
    criteria.setMaxResults(items);

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

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

    return paginationData;
}

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

@Override
public PaginationData<SellingPost> getConfirmedPost(int first, int items) {
    SQLQuery sqlQuery = getSession().createSQLQuery("");

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

    //Ly s dng//from w w w.j  a  v a  2 s .com
    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.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  a v  a 2  s.c  o  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.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);/*w ww  . j  a va 2s .  c o  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

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));
        }/*from   w  w  w .j av a  2s  .  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 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);/*  ww w. j  av  a2  s  .c  om*/
            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;
}