Example usage for org.hibernate.criterion Projections distinct

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

Introduction

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

Prototype

public static Projection distinct(Projection projection) 

Source Link

Document

Create a distinct projection from a projection.

Usage

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

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.  ja  v  a  2s  . com*/
    }

    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);//  w  w  w.  j  a  v a  2s. 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.cimmyt.model.dao.impl.LabStudyDAOImpl.java

License:Apache License

private List<Integer> getListWithSampleFilters(final List<DsSearchParam> params) {

    final List<Integer> studyIdList = this.getHibernateTemplate()
            .execute(new HibernateCallback<List<Integer>>() {
                @SuppressWarnings("unchecked")
                public List<Integer> doInHibernate(Session session) throws HibernateException, SQLException {
                    List<DsSearchParam> sampleParams = new ArrayList<DsSearchParam>();
                    for (DsSearchParam p : params) {
                        if (p.getElement().equals(VALUE_SAMPLE)) {
                            sampleParams.add(p);
                        }/*from  ww w. ja  v a2s.  c o  m*/
                    }
                    params.removeAll(sampleParams);

                    DetachedCriteria criteria = DetachedCriteria.forClass(LabStudy.class, VALUE_STUDY);
                    addCriteria(criteria, sampleParams, true);
                    criteria.setProjection(Projections.distinct(Projections.property("labstudyid")));
                    return (List<Integer>) (sampleParams.size() > 0
                            ? getHibernateTemplate().findByCriteria(criteria)
                            : null);
                }
            });
    return studyIdList;
}

From source file:com.cimmyt.model.dao.impl.SampleDetailDAOImpl.java

License:Apache License

public List<String> getPlatesNotInShipmentSet(final Integer idLabStudy, final List<String> excludingPlates) {

    List<String> listPlate = (List<String>) getHibernateTemplate()
            .execute(new HibernateCallback<List<String>>() {

                public List<String> doInHibernate(Session session) throws HibernateException, SQLException {
                    Criteria criteria = session.createCriteria(SampleDetail.class);
                    criteria.add(Restrictions.eq("labstudyid.labstudyid", idLabStudy));
                    if (excludingPlates != null && !excludingPlates.isEmpty())
                        criteria.add(Restrictions.not(Restrictions.in("platename", excludingPlates)));

                    criteria.add(Restrictions.eq("selforsend", "N"));
                    criteria.setProjection(Projections.distinct(Projections.property("platename")));
                    criteria.addOrder(Order.asc("platename"));

                    @SuppressWarnings("unchecked")
                    List<String> results = criteria.list();
                    return results;
                }/*  w w  w . j a va 2 s . com*/

            });
    return listPlate;
}

From source file:com.cms.utils.BaseFWDAOImpl.java

License:Open Source License

public List<T> findDistinct(String[] pros, Criterion[] crits) {
    ProjectionList listProjections = Projections.projectionList();
    ProjectionList listProperties = Projections.projectionList();
    Order[] orders = new Order[pros.length];
    int index = 0;
    for (String property : pros) {
        listProperties.add(Projections.property(property));
        orders[index++] = Order.asc(property);
    }//ww  w  . jav a  2s  . c o m
    listProjections.add(Projections.distinct(listProperties));
    return findByCriteria("default session", 0, 0, listProjections, crits, orders);
}

From source file:com.cristian.tareask.daoImpl.MessageReceptorDaoImpl.java

@Override
public List<Integer> getAllMessageReceptorsByConversationUnique(Integer idConversation) {
    s = HibernateUtil.getSessionFactory().openSession();
    s.beginTransaction();//  ww  w  .  j ava 2  s . c  o m
    Criteria c = s.createCriteria(MessageReceptor.class)
            .add(Restrictions.eq("emailConversation.id", idConversation))
            .setProjection(Projections.distinct(Projections.property("user.id")));
    return c.list();
}

From source file:com.cristian.tareask.daoImpl.MessageReceptorDaoImpl.java

@Override
public List<Integer> getAllMessageReceptorsByMessageUnique(Integer idMessage) {
    s = HibernateUtil.getSessionFactory().openSession();
    s.beginTransaction();/* w w  w . ja v  a  2s . com*/
    Criteria c = s.createCriteria(MessageReceptor.class)
            .setProjection(Projections.distinct(Projections.property("user.id")))
            .add(Restrictions.eq("emailMessage.id", idMessage));
    return c.list();
}

From source file:com.ephesoft.dcma.da.dao.hibernate.BatchClassDaoImpl.java

License:Open Source License

/**
 * API to get the list of Batch Classes specifying startindex, no of results and sorting if any.
 * //w  w w . j a  v  a 2  s  . c  o m
 * @param firstResult int
 * @param maxResults int 
 * @param order List<Order>
 * @param userRoles Set<String>
 * @return List of batch class.
 */
@Override
public List<BatchClass> getBatchClassList(final int firstResult, final int maxResults, final List<Order> order,
        final Set<String> userRoles) {
    EphesoftCriteria criteria = criteria();
    List<BatchClass> batchClassList = null;
    if (userRoles == null) {
        batchClassList = new ArrayList<BatchClass>(0);
    } else {
        List<String> roleList = new ArrayList<String>();
        for (String userRole : userRoles) {
            if (null == userRole || userRole.isEmpty()) {
                continue;
            }
            roleList.add(userRole);
        }
        DetachedCriteria detachedCriteria = criteria();
        detachedCriteria.createAlias(ASSIGNED_GROUPS, ASSIGNED_GROUPS);
        detachedCriteria.add(Restrictions.in(ASSIGNED_GROUPS_NAME, roleList));
        detachedCriteria.setProjection(Projections.distinct(Projections.property(BATCH_ID)));
        criteria.add(Subqueries.propertyIn(BATCH_ID, detachedCriteria));
        criteria.add(Restrictions.or(Restrictions.isNull(IS_DELETED), Restrictions.eq(IS_DELETED, false)));
        batchClassList = find(criteria, firstResult, maxResults, order.toArray(new Order[order.size()]));
    }
    return batchClassList;
}