Example usage for org.hibernate Criteria setMaxResults

List of usage examples for org.hibernate Criteria setMaxResults

Introduction

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

Prototype

public Criteria setMaxResults(int maxResults);

Source Link

Document

Set a limit upon the number of objects to be retrieved.

Usage

From source file:com.apt.facade.BatchFacade.java

public List<Batch> getBatchList(BatchFinder finder, int page, int recordPerPage) {
    List<Batch> lst = new ArrayList<>();

    Session session = null;//from   w  w  w .  j  av  a2 s.c o  m
    Transaction trans = null;

    try {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        trans = session.beginTransaction();

        Criteria crit = session.createCriteria(Batch.class);
        crit.add(Restrictions.sqlRestriction("1=1"));
        if (finder.getBatchId() != null) {
            crit.add(Restrictions.and(Restrictions.eq("batchId", finder.getBatchId())));
        }
        if (finder.getBatchName() != null) {
            crit.add(Restrictions.and(Restrictions.ilike("batchName", "%" + finder.getBatchName() + "%")));
        }
        crit.setFirstResult((page - 1) * recordPerPage);
        crit.setMaxResults(recordPerPage);
        lst = crit.list();
        trans.commit();

    } catch (Exception e) {
        e.printStackTrace();
        if (trans != null) {
            trans.rollback();
        }
    } finally {
        if (session != null && session.isConnected()) {
            session.close();
        }
    }

    return lst;
}

From source file:com.apt.facade.StudentFacade.java

public List<Student> getStudentList(StudentFinder finder, int page, int recordPerPage) {
    List<Student> lst = new ArrayList<>();

    Session session = null;/* ww w .ja v a  2  s.  c  om*/
    Transaction trans = null;

    try {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        trans = session.beginTransaction();

        Criteria crit = session.createCriteria(Student.class);

        crit.add(Restrictions.sqlRestriction("1=1"));
        if (finder.getStudentId() != null) {
            crit.add(Restrictions.and(Restrictions.eq("studentId", finder.getStudentId())));
        }
        if (finder.getStudentName() != null) {
            crit.add(Restrictions.and(Restrictions.ilike("studentName", "%" + finder.getStudentName() + "%")));
        }
        if (finder.getBatch() != null) {
            crit.createAlias("batch", "a");
            Criterion rest = Restrictions.or(Restrictions.eq("a.batchId", finder.getBatch().getBatchId()),
                    Restrictions.eq("a.batchName", finder.getBatch().getBatchName()));
            crit.add(Restrictions.and(rest));
        }
        crit.setFirstResult((page - 1) * recordPerPage);
        crit.setMaxResults(recordPerPage);
        lst = crit.list();
        trans.commit();

    } catch (Exception e) {
        e.printStackTrace();
        if (trans != null) {
            trans.rollback();
        }
    } finally {
        if (session != null && session.isConnected()) {
            session.close();
        }
    }

    return lst;
}

From source file:com.apt.facade.SubjectFacade.java

public List<Subject> getSubjectList(SubjectFinder finder, int page, int recordPerPage) {
    List<Subject> lst = new ArrayList<>();

    Session session = null;//w  w w.j  ava2  s  .  co  m
    Transaction trans = null;

    try {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        trans = session.beginTransaction();

        Criteria crit = session.createCriteria(Subject.class);
        crit.add(Restrictions.sqlRestriction("1=1"));
        if (finder.getSubjectId() != null) {
            crit.add(Restrictions.and(Restrictions.eq("subjectId", finder.getSubjectId())));
        }
        if (finder.getSubjectName() != null) {
            crit.add(Restrictions.and(Restrictions.ilike("subjectName", "%" + finder.getSubjectName() + "%")));
        }
        crit.setFirstResult((page - 1) * recordPerPage);
        crit.setMaxResults(recordPerPage);
        lst = crit.list();
        trans.commit();

    } catch (Exception e) {
        e.printStackTrace();
        if (trans != null) {
            trans.rollback();
        }
    } finally {
        if (session != null && session.isConnected()) {
            session.close();
        }
    }

    return lst;
}

From source file:com.axway.academy.addressbook.core.AccountManagerImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   ww w.ja v a2  s .co m*/
public List<AddressBookEntry> getAddressBookContacts(AddressBookEntryCriterion criterion, Integer first,
        Integer count) throws NoSuchAccountException {
    Session session = mSessionFactoryManager.getSessionFactory().openSession();

    try {
        if (criterion == null) {
            throw new NoSuchAccountException("AddressBookEntryCriterion not valid");
        }

        Criteria criteria = ((AddressBookEntryCriterionImpl) criterion).getCriteria(session);

        if (first != null) {
            criteria.setFirstResult(first);
        }

        if (count != null) {
            criteria.setMaxResults(count);
        }

        return criteria.list();

    } finally {
        SessionManagerFactory.closeSession(session);
    }
}

From source file:com.Bean.PostinfoHelper.java

public List<Post> searchByCriteria(PostSearcher postSearcher, int page) {

    List<Post> postList = new ArrayList<Post>();
    try {//from   ww w  .  j a v  a 2  s. co  m
        Criteria c = session.createCriteria(Post.class);
        if (postSearcher.getTitle() != null) {
            c.add(Restrictions.like("title", "%" + postSearcher.getTitle() + "%"));
        }
        if ((postSearcher.getMinPrice() >= 0) && (postSearcher.getMaxPrice() >= 0)) {
            c.add(Restrictions.between("price", postSearcher.getMinPrice(), postSearcher.getMaxPrice()));
        } else if (postSearcher.getMinPrice() >= 0) {
            c.add(Restrictions.ge("price", postSearcher.getMinPrice()));
        } else if (postSearcher.getMaxPrice() >= 0) {
            c.add(Restrictions.le("price", postSearcher.getMaxPrice()));
        }
        if (postSearcher.getTypes() != null) {
            c.add(Restrictions.in("type", postSearcher.getTypes()));
        }
        maxPage = c.list().size() / itemsPerPage;
        c.setFirstResult(page * itemsPerPage);
        c.setMaxResults(itemsPerPage);
        postList = (List<Post>) c.list();
        return postList;
    } catch (HibernateException e) {
        System.err.println(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.bean.StatisticBean.java

public List<Object[]> getTopUserMostPost() {
    Dao dao = new Dao();
    Criteria c = dao.createCriteria(Property.class);
    ProjectionList proj = Projections.projectionList();
    proj.add(Projections.groupProperty("users"));
    proj.add(Projections.rowCount(), "Count");
    c.setProjection(proj);/*  w  w w. ja v a 2s  .c  o m*/
    c.addOrder(Order.desc("Count"));
    c.setFirstResult(0);
    c = selectTopUserMostPost == 0 ? c.setMaxResults(10) : c.setMaxResults(selectTopUserMostPost);
    List<Object[]> a = c.list();
    return a;
}

From source file:com.bean.StatisticBean.java

public List<Object[]> getTopPostMostFav() {
    Dao dao = new Dao();
    Criteria c = dao.createCriteria(FavoriteProperty.class);
    ProjectionList proj = Projections.projectionList();
    proj.add(Projections.groupProperty("property"));
    proj.add(Projections.rowCount(), "Count");
    c.setProjection(proj);//from   ww w  .  j ava  2 s . c  o m
    c.addOrder(Order.desc("Count"));
    c.setFirstResult(0);
    c = selectTopPostMostFav == 0 ? c.setMaxResults(10) : c.setMaxResults(selectTopPostMostFav);
    List<Object[]> a = c.list();
    return a;
}

From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.java

License:Open Source License

/**
 * Construct a JBPM Hibernate query based on the Task Query provided
 * /* www  .  j ava2  s.  c om*/
 * @param session
 * @param query
 * @return  jbpm hiberate query criteria
 */
private Criteria createTaskQueryCriteria(Session session, WorkflowTaskQuery query) {
    Criteria task = session.createCriteria(TaskInstance.class);

    // task id
    if (query.getTaskId() != null) {
        task.add(Restrictions.eq("id", getJbpmId(query.getTaskId())));
    }

    // task state
    if (query.getTaskState() != null) {
        WorkflowTaskState state = query.getTaskState();
        if (state == WorkflowTaskState.IN_PROGRESS) {
            task.add(Restrictions.eq("isOpen", true));
            task.add(Restrictions.isNull("end"));
        } else if (state == WorkflowTaskState.COMPLETED) {
            task.add(Restrictions.eq("isOpen", false));
            task.add(Restrictions.isNotNull("end"));
        }
    }

    // task name
    if (query.getTaskName() != null) {
        task.add(Restrictions.eq("name", query.getTaskName().toPrefixString(namespaceService)));
    }

    // task actor
    if (query.getActorId() != null) {
        task.add(Restrictions.eq("actorId", query.getActorId()));
    }

    // task custom properties
    if (query.getTaskCustomProps() != null) {
        Map<QName, Object> props = query.getTaskCustomProps();
        if (props.size() > 0) {
            Criteria variables = task.createCriteria("variableInstances");
            Disjunction values = Restrictions.disjunction();
            for (Map.Entry<QName, Object> prop : props.entrySet()) {
                Conjunction value = Restrictions.conjunction();
                value.add(Restrictions.eq("name", factory.mapQNameToName(prop.getKey())));
                value.add(Restrictions.eq("value", prop.getValue().toString()));
                values.add(value);
            }
            variables.add(values);
        }
    }

    // process criteria
    Criteria process = createProcessCriteria(task, query);

    // process custom properties
    if (query.getProcessCustomProps() != null) {
        // TODO: Due to Hibernate bug
        // http://opensource.atlassian.com/projects/hibernate/browse/HHH-957
        // it's not possible to perform a sub-select with the criteria api.
        // For now issue a
        //       secondary query and create an IN clause.
        Map<QName, Object> props = query.getProcessCustomProps();
        if (props.size() > 0) {
            // create criteria for process variables
            Criteria variables = session.createCriteria(VariableInstance.class);
            variables.setProjection(Projections.distinct(Property.forName("processInstance")));
            Disjunction values = Restrictions.disjunction();
            for (Map.Entry<QName, Object> prop : props.entrySet()) {
                Conjunction value = Restrictions.conjunction();
                value.add(Restrictions.eq("name", factory.mapQNameToName(prop.getKey())));
                value.add(Restrictions.eq("value", prop.getValue().toString()));
                values.add(value);
            }
            variables.add(values);

            // note: constrain process variables to same criteria as tasks
            createProcessCriteria(variables, query);

            Disjunction processIdCriteria = createProcessIdCriteria(variables);

            // constrain tasks by process list
            process = (process == null) ? task.createCriteria("processInstance") : process;
            process.add(processIdCriteria);
        }
    }

    // order by
    if (query.getOrderBy() != null) {
        WorkflowTaskQuery.OrderBy[] orderBy = query.getOrderBy();
        for (WorkflowTaskQuery.OrderBy orderByPart : orderBy) {
            if (orderByPart == WorkflowTaskQuery.OrderBy.TaskActor_Asc) {
                task.addOrder(Order.asc("actorId"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskActor_Desc) {
                task.addOrder(Order.desc("actorId"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskCreated_Asc) {
                task.addOrder(Order.asc("create"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskCreated_Desc) {
                task.addOrder(Order.desc("create"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskDue_Asc) {
                task.addOrder(Order.asc("dueDate"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskDue_Desc) {
                task.addOrder(Order.desc("dueDate"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskId_Asc) {
                task.addOrder(Order.asc("id"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskId_Desc) {
                task.addOrder(Order.desc("id"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskName_Asc) {
                task.addOrder(Order.asc("name"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskName_Desc) {
                task.addOrder(Order.desc("name"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskState_Asc) {
                task.addOrder(Order.asc("end"));
            } else if (orderByPart == WorkflowTaskQuery.OrderBy.TaskState_Desc) {
                task.addOrder(Order.desc("end"));
            }
        }
    }

    // limit results
    if (query.getLimit() != -1) {
        task.setMaxResults(query.getLimit());
    }

    return task;
}

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

@Override
public PaginationData get(int first, int items) {
    Criteria criteria = getSession().createCriteria(registeredClass());
    criteria.setFirstResult(first);/*from   w ww.  j  a  v  a  2 s . c  o  m*/
    criteria.setMaxResults(items);
    List<T> entities = criteria.list();
    HibernateInitSupport.setCls(registeredClass());
    for (T e : entities)
        HibernateInitSupport.initDomain((T) e);

    PaginationData paginationData = new PaginationData(count(), items, first, entities);
    return paginationData;
}

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

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

    criteria.setFirstResult(first);//w  w w .  j  a  v a2 s  . c  om
    criteria.setMaxResults(items);

    Set<SellerInvoice> sellerInvoices = new HashSet<>(criteria.list());
    HibernateInitSupport.setCls(SellerInvoice.class);
    for (SellerInvoice invoice : sellerInvoices)
        HibernateInitSupport.initDomain(invoice);

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

    return paginationData;
}