Example usage for org.hibernate Query setMaxResults

List of usage examples for org.hibernate Query setMaxResults

Introduction

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

Prototype

@Override
    Query<R> setMaxResults(int maxResult);

Source Link

Usage

From source file:com.gcrm.dao.BaseDao.java

License:Apache License

@SuppressWarnings("unchecked")
public SearchResult<T> getPaginationObjects(final String clazz, final SearchCondition searchCondition) {

    List<T> objects = null;

    final String condition = searchCondition.getCondition();

    objects = getHibernateTemplate().executeFind(new HibernateCallback<List<T>>() {

        public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
            String hql = INIT_HQL + clazz;
            if (condition != null && condition.length() > 0) {
                hql += " where ";
                hql += condition;//from ww  w  .  ja  v  a 2 s .  c  o  m
            }
            hql += " order by " + searchCondition.getSidx() + " "

                    + searchCondition.getSord();
            int pageSize = searchCondition.getPageSize();
            int pageNo = searchCondition.getPageNo();

            Query query = session.createQuery(hql);

            if (pageNo != 0 && pageSize != 0) {
                int rowNumber = (pageNo - 1) * pageSize;
                query.setFirstResult(rowNumber);
                query.setMaxResults(pageSize);
            }
            List<T> list = query.list();

            return list;
        }
    });

    long count = 0;
    String countHql = "select count(*) from " + clazz;
    if (condition != null && condition.length() > 0) {
        countHql += " where ";
        countHql += condition;
    }

    count = (Long) getHibernateTemplate().find(countHql).get(0);
    SearchResult<T> result = new SearchResult<T>(count, objects);

    return result;
}

From source file:com.gcrm.dao.impl.BaseDao.java

License:Apache License

@SuppressWarnings("unchecked")
public SearchResult<T> getPaginationObjects(final String clazz, final String columns,
        final SearchCondition searchCondition) {

    List<T> objects = null;

    final String condition = searchCondition.getCondition();

    objects = getHibernateTemplate().executeFind(new HibernateCallback() {

        public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
            StringBuilder hqlBuilder = new StringBuilder("");
            if (columns != null) {
                hqlBuilder.append(SELECT_HQL).append(columns).append(" ");
            }/*  w ww. j a  va2 s.  c om*/
            hqlBuilder.append(FROM_HQL).append(clazz);
            if (condition != null && condition.length() > 0) {
                hqlBuilder.append(" where ");
                hqlBuilder.append(condition);
            }
            hqlBuilder.append(" order by ").append(searchCondition.getSidx()).append(" ")
                    .append(searchCondition.getSord());
            int pageSize = searchCondition.getPageSize();
            int pageNo = searchCondition.getPageNo();

            Query query = session.createQuery(hqlBuilder.toString());

            if (pageNo != 0 && pageSize != 0) {
                int rowNumber = (pageNo - 1) * pageSize;
                query.setFirstResult(rowNumber);
                query.setMaxResults(pageSize);
            }
            List<T> list = query.list();

            return list;
        }
    });

    long count = 0;
    String countHql = "select count(*) from " + clazz;
    if (condition != null && condition.length() > 0) {
        countHql += " where ";
        countHql += condition;
    }

    count = (Long) getHibernateTemplate().find(countHql).get(0);
    SearchResult<T> result = new SearchResult<T>(count, objects);

    return result;
}

From source file:com.gisgraphy.domain.repository.GenericDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<T> getAllPaginate(final int from, final int maxResults) {
    return (List<T>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            String queryString = "from " + persistentClass.getSimpleName() + " order by id";
            //we order by id because we want to keep the same order query after query

            Query qry = session.createQuery(queryString);
            qry.setCacheable(true);// ww w. j  a v  a  2  s  .com
            if (maxResults > 0) {
                qry.setMaxResults(maxResults);
            }
            if (from >= 1) {
                qry.setFirstResult(from - 1);
            }
            List<T> results = (List<T>) qry.list();
            if (results == null) {
                results = new ArrayList<T>();
            }
            return results;
        }
    });

}

From source file:com.gisgraphy.domain.repository.OpenStreetMapDao.java

License:Open Source License

public OpenStreetMap getByOpenStreetMapId(final Long openstreetmapId) {
    Assert.notNull(openstreetmapId);//from ww  w . j  a  v a 2 s .c o  m
    return (OpenStreetMap) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            String queryString = "from " + OpenStreetMap.class.getSimpleName()
                    + " as c where c.openstreetmapId= ?";

            Query qry = session.createQuery(queryString);
            qry.setMaxResults(1);
            //we need to limit to 1 because a street can be in two countries
            qry.setCacheable(true);

            qry.setParameter(0, openstreetmapId);

            OpenStreetMap result = (OpenStreetMap) qry.uniqueResult();
            return result;
        }
    });
}

From source file:com.github.auto1st.rundeck.plugin.JobExecutionConditional.java

License:Apache License

@Override
public void executeStep(final PluginStepContext context, final Map<String, Object> map) throws StepException {

    /*/*w w w. j ava 2  s . c  o m*/
     * Get the job service from context.
     */
    final JobService jobService = context.getExecutionContext().getJobService();

    /*
     * Extract options from optionCondition
     */
    final Map<String, String> _conditions = Utils.conditionsOf(optionCondition);
    final Set<String> _conditionsKeys = _conditions.keySet();

    /*
     * Hack to get the hibernate session from Grails APP
     */
    final GrailsApplication grails = Holders.getGrailsApplication();
    final ApplicationContext mainContext = grails.getMainContext();
    final SessionFactory factory = (SessionFactory) mainContext.getBean(SESSION_FACTORY);
    Session session = null;

    try {
        /*
         * Get the job reference by UUID
         */
        final JobReference job = jobService.jobForID(jobUUID, context.getFrameworkProject());

        /*
         * Log the job name.
         */
        context.getLogger().log(2, "Job Name: " + job.getJobAndGroup());

        /*
         * Start a new hibernate session.
         */
        session = factory.openSession();

        /*
         * Query.
         */
        Query query = null;

        /*
         * Analyzed failed?
         */
        if (Boolean.TRUE.equals(analyzeFailed)) {

            //yes, query the succeeded or failed
            query = session.createQuery(EXECUTIONS_QUERY_ALL_SUCCEEDED_OR_OTHER);
            query.setParameter(EXECUTIONS_QUERY_ALL_PARAM1, STATUS_FAILED);

        } else {

            //no, select just the succeeded
            query = session.createQuery(EXECUTIONS_QUERY_ALL_SUCCEEDED);

        }

        //set the job uuid
        query.setParameter(EXECUTIONS_QUERY_ALL_PARAM0, job.getId());

        //is there maximum executions?
        if (maximumExecutions > 0) {
            query.setMaxResults(maximumExecutions);
        }

        // execute the query
        final List<?> _executions = query.list();

        /*
         * At then end if it has true, conditions are met
         */
        boolean _continue = _executions.size() > 0;

        /*
         * For each execution.
         */
        for (int _index = 0; _index < _executions.size(); _index++) {
            Object _execution = _executions.get(_index);

            // local boolean accumulator
            boolean _local = true;

            /*
             * Get the argString value. The options list used by the execution.
             */
            Object _argStringObj = MethodUtils.invokeMethod(_execution, METHOD_GET_ARGSTRING);

            if (_argStringObj instanceof String) {

                /*
                 * Extract the pairs from argString used by the Execution
                 */
                Map<String, String> _options = Utils.optionsOf((String) _argStringObj);

                /*
                 * For each condition
                 */
                for (String _key : _conditionsKeys) {
                    // compare the condition value to execution option value
                    _local = _local && _conditions.get(_key).equals(_options.get(_key));
                }
            }

            // compare holder
            _continue = _local;

            /*
             * When the first true compare is found, breaks the loop.
             */
            if (_local) {
                break;
            }
        }

        if (_continue) {
            // conditions are met
            context.getLogger().log(2, "Conditions are met: " + _conditions);
        } else {
            // conditions aren't met
            context.getLogger().log(0, "Conditions aren't met: " + _conditions);
            context.getFlowControl().Halt(message);
        }

    } catch (Exception e) {
        throw new StepException(e.getMessage(), e, Failures.GeneralFailure);
    } finally {
        if (null != session) {
            // close the hibernate session
            session.close();
        }
    }
}

From source file:com.glaf.jbpm.dao.JbpmEntityDAO.java

License:Apache License

public List<Object> getList(JbpmContext jbpmContext, int currPageNo, int maxResults,
        SqlExecutor queryExecutor) {/*from  w ww . j a  v  a 2s  .c o m*/
    Session session = jbpmContext.getSession();
    Query query = session.createQuery(queryExecutor.getSql());
    Object parameter = queryExecutor.getParameter();
    if (parameter instanceof Map) {
        Map<String, Object> params = (Map<String, Object>) parameter;

        if (params != null && params.size() > 0) {
            Set<Entry<String, Object>> entrySet = params.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String name = entry.getKey();
                Object value = entry.getValue();
                if (value != null) {
                    if (value instanceof Collection) {
                        query.setParameterList(name, (Collection<?>) value);
                    } else {
                        query.setParameter(name, value);
                    }
                }
            }
        }
    }

    query.setFirstResult((currPageNo - 1) * maxResults);
    query.setMaxResults(maxResults);

    List<Object> rows = query.list();
    return rows;
}

From source file:com.glaf.jbpm.dao.JbpmEntityDAO.java

License:Apache License

public Paging getPage(JbpmContext jbpmContext, int currPageNo, int pageSize, SqlExecutor countExecutor,
        SqlExecutor queryExecutor) {/* w ww .  ja v a 2s. com*/
    Session session = jbpmContext.getSession();
    Paging page = new Paging();
    if (pageSize <= 0) {
        pageSize = Paging.DEFAULT_PAGE_SIZE;
    }
    if (currPageNo <= 0) {
        currPageNo = 1;
    }
    int totalCount = 0;
    if (countExecutor != null) {
        Object obj = null;
        String hql = countExecutor.getSql();
        hql = removeOrders(hql);
        Query q = session.createQuery(hql);

        Object parameter = queryExecutor.getParameter();
        if (parameter instanceof Map) {
            Map<String, Object> params = (Map<String, Object>) parameter;

            if (params != null && params.size() > 0) {
                Set<Entry<String, Object>> entrySet = params.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (value != null) {
                        if (value instanceof Collection) {
                            q.setParameterList(name, (Collection<?>) value);
                        } else {
                            q.setParameter(name, value);
                        }
                    }
                }
            }
        }

        obj = q.iterate().next();

        if (obj instanceof Integer) {
            Integer iCount = (Integer) obj;
            totalCount = iCount.intValue();
        } else if (obj instanceof Long) {
            Long iCount = (Long) obj;
            totalCount = iCount.intValue();
        } else if (obj instanceof BigDecimal) {
            BigDecimal bg = (BigDecimal) obj;
            totalCount = bg.intValue();
        } else if (obj instanceof BigInteger) {
            BigInteger bi = (BigInteger) obj;
            totalCount = bi.intValue();
        }

    } else {
        List<Object> list = null;
        Query q = session.createQuery(queryExecutor.getSql());

        Object parameter = queryExecutor.getParameter();
        if (parameter instanceof Map) {
            Map<String, Object> params = (Map<String, Object>) parameter;

            if (params != null && params.size() > 0) {
                Set<Entry<String, Object>> entrySet = params.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (value != null) {
                        if (value instanceof Collection) {
                            q.setParameterList(name, (Collection<?>) value);
                        } else {
                            q.setParameter(name, value);
                        }
                    }
                }
            }
        }

        list = q.list();
        if (list != null) {
            totalCount = list.size();
        }
    }

    if (totalCount == 0) {
        page.setRows(new java.util.ArrayList<Object>());
        page.setCurrentPage(0);
        page.setPageSize(0);
        page.setTotal(0);
        return page;
    }
    page.setTotal(totalCount);

    int maxPageNo = (page.getTotal() + (pageSize - 1)) / pageSize;
    if (currPageNo > maxPageNo) {
        currPageNo = maxPageNo;
    }

    Query query = session.createQuery(queryExecutor.getSql());

    Object parameter = queryExecutor.getParameter();
    if (parameter instanceof Map) {
        Map<String, Object> params = (Map<String, Object>) parameter;
        if (params != null && params.size() > 0) {
            Set<Entry<String, Object>> entrySet = params.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String name = entry.getKey();
                Object value = entry.getValue();
                if (value != null) {
                    if (value instanceof Collection) {
                        query.setParameterList(name, (Collection<?>) value);
                    } else {
                        query.setParameter(name, value);
                    }
                }
            }
        }
    }

    query.setFirstResult((currPageNo - 1) * pageSize);
    query.setMaxResults(pageSize);

    List<Object> list = query.list();
    page.setRows(list);
    page.setPageSize(pageSize);
    page.setCurrentPage(currPageNo);

    return page;
}

From source file:com.glaf.jbpm.dao.JbpmTaskDAO.java

License:Apache License

/**
 * ???/*from w w w  .  j  a va  2s .c o m*/
 * 
 * @param jbpmContext
 * @param paramMap
 * @return
 */
public List<TaskInstance> getFinishedTaskInstances(JbpmContext jbpmContext, ProcessQuery query) {
    StringBuffer buffer = new StringBuffer();
    buffer.append(
            " select ti from org.jbpm.taskmgmt.exe.TaskInstance as ti where ti.actorId is not null and ti.start is not null and ti.end is not null and ti.isSuspended != true and ti.isOpen = false ");

    Map<String, Object> params = new java.util.HashMap<String, Object>();

    if (query.getActorId() != null) {
        buffer.append(" and ti.actorId = :actorId ");
        params.put("actorId", query.getActorId());
    }

    if (query.getActorIds() != null && !query.getActorIds().isEmpty()) {
        Collection<String> collection = query.getActorIds();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "actorId_" + index;
                buffer.append(" ti.actorId = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getProcessInstanceId() != null) {
        buffer.append(" and ti.processInstance.id = :processInstanceId ");
        params.put("processInstanceId", query.getProcessInstanceId());
    }

    if (query.getProcessInstanceIds() != null && !query.getProcessInstanceIds().isEmpty()) {
        Collection<Long> collection = query.getProcessInstanceIds();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Long pid : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "processInstanceId_" + index;
                buffer.append(" ti.processInstance.id = :").append(p_name);

                params.put(p_name, pid);

                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getTaskName() != null) {
        buffer.append(" and ti.name like :taskName ");
        params.put("taskName", "%" + query.getTaskName() + "%");
    }

    if (query.getTaskNames() != null && !query.getTaskNames().isEmpty()) {
        Collection<String> collection = query.getTaskNames();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "taskName_" + index;
                buffer.append(" ti.name = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getAfterTaskCreateDate() != null) {
        params.put("afterTaskCreateDate", query.getAfterTaskCreateDate());
        buffer.append(" and ( ti.create >= :afterTaskCreateDate )");
    }

    if (query.getBeforeTaskCreateDate() != null) {
        params.put("beforeTaskCreateDate", query.getBeforeTaskCreateDate());
        buffer.append(" and ( ti.create <= :beforeTaskCreateDate )");
    }

    if (query.getAfterTaskStartDate() != null) {
        params.put("afterTaskStartDate", query.getAfterTaskStartDate());
        buffer.append(" and ( ti.start >= :afterTaskStartDate )");
    }

    if (query.getBeforeTaskStartDate() != null) {
        params.put("beforeTaskStartDate", query.getBeforeTaskStartDate());
        buffer.append(" and ( ti.start <= :beforeTaskStartDate )");
    }

    if (query.getAfterTaskEndDate() != null) {
        params.put("afterTaskEndDate", query.getAfterTaskEndDate());
        buffer.append(" and ( ti.end >= :afterTaskEndDate )");
    }

    if (query.getBeforeTaskEndDate() != null) {
        params.put("beforeTaskEndDate", query.getBeforeTaskEndDate());
        buffer.append(" and ( ti.end <= :beforeTaskEndDate )");
    }

    if (query.getTaskType() != null) {
        if (StringUtils.equals(query.getTaskType(), "running")) {
            buffer.append(" and ti.end is null ");
        } else if (StringUtils.equals(query.getTaskType(), "finished")) {
            buffer.append(" and ti.end is not null ");
        }
    }

    if (query.getProcessName() != null) {
        params.put("processName", query.getProcessName());
        buffer.append(" and ti.processInstance.name = :processName ");
    }

    if (query.getProcessNames() != null && !query.getProcessNames().isEmpty()) {
        Collection<String> collection = query.getProcessNames();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "processName_" + index;
                buffer.append(" ti.processInstance.processDefinition.name = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getProcessDefinitionId() != null) {
        buffer.append(" and ti.processInstance.processDefinition.id = :processDefinitionId ");
        params.put("processDefinitionId", query.getProcessDefinitionId());
    }

    if (LogUtils.isDebug()) {
        logger.debug(buffer.toString());
    }

    Session session = jbpmContext.getSession();
    Query q = session.createQuery(buffer.toString());
    q.setMaxResults(5000);

    if (params != null && params.size() > 0) {
        Set<Entry<String, Object>> entrySet = params.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                q.setParameter(name, value);
            }
        }
    }

    List<?> rows = q.list();
    List<TaskInstance> taskInstances = new java.util.ArrayList<TaskInstance>();
    if (rows != null && rows.size() > 0) {
        Iterator<?> iterator = rows.iterator();
        while (iterator.hasNext()) {
            taskInstances.add((TaskInstance) iterator.next());
        }
    }

    return taskInstances;
}

From source file:com.glaf.jbpm.dao.JbpmTaskDAO.java

License:Apache License

public List<TaskInstance> getPooledTaskInstances(JbpmContext jbpmContext, ProcessQuery query) {
    StringBuffer buffer = new StringBuffer();
    buffer.append(//from  w w  w  .j av a  2s .  com
            " select ti from org.jbpm.taskmgmt.exe.PooledActor pooledActor join pooledActor.taskInstances ti where 1=1 and ti.actorId is null and ti.isSuspended != true and ti.isOpen = true and ti.processInstance.end is null ");
    Map<String, Object> params = new java.util.HashMap<String, Object>();

    if (query.getActorId() != null) {
        buffer.append(" and pooledActor.actorId = :actorId ");
        params.put("actorId", query.getActorId());
    }

    if (query.getActorIds() != null && !query.getActorIds().isEmpty()) {
        Collection<String> collection = query.getActorIds();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "actorId_" + index;
                buffer.append(" pooledActor.actorId = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getProcessInstanceId() != null) {
        buffer.append(" and ti.processInstance.id = :processInstanceId ");
        params.put("processInstanceId", query.getProcessInstanceId());
    }

    if (query.getProcessInstanceIds() != null && !query.getProcessInstanceIds().isEmpty()) {
        Collection<Long> collection = query.getProcessInstanceIds();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Long pid : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "processInstanceId_" + index;
                buffer.append(" ti.processInstance.id = :").append(p_name);

                params.put(p_name, pid);

                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getTaskName() != null) {
        buffer.append(" and ti.name like :taskName ");
        params.put("taskName", "%" + query.getTaskName() + "%");
    }

    if (query.getTaskNames() != null && !query.getTaskNames().isEmpty()) {
        Collection<String> collection = query.getTaskNames();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "taskName_" + index;
                buffer.append(" ti.name = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getAfterTaskCreateDate() != null) {
        params.put("afterTaskCreateDate", query.getAfterTaskCreateDate());
        buffer.append(" and ( ti.create >= :afterTaskCreateDate )");
    }

    if (query.getBeforeTaskCreateDate() != null) {
        params.put("beforeTaskCreateDate", query.getBeforeTaskCreateDate());
        buffer.append(" and ( ti.create <= :beforeTaskCreateDate )");
    }

    if (query.getAfterTaskStartDate() != null) {
        params.put("afterTaskStartDate", query.getAfterTaskStartDate());
        buffer.append(" and ( ti.start >= :afterTaskStartDate )");
    }

    if (query.getBeforeTaskStartDate() != null) {
        params.put("beforeTaskStartDate", query.getBeforeTaskStartDate());
        buffer.append(" and ( ti.start <= :beforeTaskStartDate )");
    }

    if (query.getAfterTaskEndDate() != null) {
        params.put("afterTaskEndDate", query.getAfterTaskEndDate());
        buffer.append(" and ( ti.end >= :afterTaskEndDate )");
    }

    if (query.getBeforeTaskEndDate() != null) {
        params.put("beforeTaskEndDate", query.getBeforeTaskEndDate());
        buffer.append(" and ( ti.end <= :beforeTaskEndDate )");
    }

    if (query.getTaskType() != null) {
        if (StringUtils.equals(query.getTaskType(), "running")) {
            buffer.append(" and ti.end is null ");
        } else if (StringUtils.equals(query.getTaskType(), "finished")) {
            buffer.append(" and ti.end is not null ");
        }
    }

    if (query.getProcessName() != null) {
        params.put("processName", query.getProcessName());
        buffer.append(" and ti.processInstance.name = :processName ");
    }

    if (query.getProcessNames() != null && !query.getProcessNames().isEmpty()) {
        Collection<String> collection = query.getProcessNames();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "processName_" + index;
                buffer.append(" ti.processInstance.processDefinition.name = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getProcessDefinitionId() != null) {
        buffer.append(" and ti.processInstance.processDefinition.id = :processDefinitionId ");
        params.put("processDefinitionId", query.getProcessDefinitionId());
    }

    if (LogUtils.isDebug()) {
        logger.debug(buffer.toString());
    }

    Session session = jbpmContext.getSession();
    Query q = session.createQuery(buffer.toString());
    q.setMaxResults(5000);

    if (params != null && params.size() > 0) {
        Set<Entry<String, Object>> entrySet = params.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                q.setParameter(name, value);
            }
        }
    }

    List<?> rows = q.list();
    List<TaskInstance> taskInstances = new java.util.ArrayList<TaskInstance>();
    if (rows != null && rows.size() > 0) {
        Iterator<?> iterator = rows.iterator();
        while (iterator.hasNext()) {
            taskInstances.add((TaskInstance) iterator.next());
        }
    }

    return taskInstances;
}

From source file:com.glaf.jbpm.dao.JbpmTaskDAO.java

License:Apache License

public List<TaskInstance> getTaskInstances(JbpmContext jbpmContext, ProcessQuery query) {
    StringBuffer buffer = new StringBuffer();
    buffer.append(/*  w ww  .j av  a  2 s . com*/
            "  select ti from org.jbpm.taskmgmt.exe.TaskInstance as ti where ti.actorId is not null and ti.isSuspended != true and ti.isOpen = true and ti.processInstance.end is null ");

    Map<String, Object> params = new java.util.HashMap<String, Object>();

    if (query.getActorId() != null) {
        buffer.append(" and ti.actorId = :actorId ");
        params.put("actorId", query.getActorId());
    }

    if (query.getActorIds() != null && !query.getActorIds().isEmpty()) {
        Collection<String> collection = query.getActorIds();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "actorId_" + index;
                buffer.append(" ti.actorId = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getProcessInstanceId() != null) {
        buffer.append(" and ti.processInstance.id = :processInstanceId ");

        params.put("processInstanceId", query.getProcessInstanceId());

    }

    if (query.getProcessInstanceIds() != null && !query.getProcessInstanceIds().isEmpty()) {
        Collection<Long> collection = query.getProcessInstanceIds();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Long pid : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "processInstanceId_" + index;
                buffer.append(" ti.processInstance.id = :").append(p_name);

                params.put(p_name, pid);

                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getTaskName() != null) {
        buffer.append(" and ti.name like :taskName ");
        params.put("taskName", "%" + query.getTaskName() + "%");
    }

    if (query.getTaskNames() != null && !query.getTaskNames().isEmpty()) {
        Collection<String> collection = query.getTaskNames();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "taskName_" + index;
                buffer.append(" ti.name = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getAfterTaskCreateDate() != null) {
        params.put("afterTaskCreateDate", query.getAfterTaskCreateDate());
        buffer.append(" and ( ti.create >= :afterTaskCreateDate )");
    }

    if (query.getBeforeTaskCreateDate() != null) {
        params.put("beforeTaskCreateDate", query.getBeforeTaskCreateDate());
        buffer.append(" and ( ti.create <= :beforeTaskCreateDate )");
    }

    if (query.getAfterTaskStartDate() != null) {
        params.put("afterTaskStartDate", query.getAfterTaskStartDate());
        buffer.append(" and ( ti.start >= :afterTaskStartDate )");
    }

    if (query.getBeforeTaskStartDate() != null) {
        params.put("beforeTaskStartDate", query.getBeforeTaskStartDate());
        buffer.append(" and ( ti.start <= :beforeTaskStartDate )");
    }

    if (query.getAfterTaskEndDate() != null) {
        params.put("afterTaskEndDate", query.getAfterTaskEndDate());
        buffer.append(" and ( ti.end >= :afterTaskEndDate )");
    }

    if (query.getBeforeTaskEndDate() != null) {
        params.put("beforeTaskEndDate", query.getBeforeTaskEndDate());
        buffer.append(" and ( ti.end <= :beforeTaskEndDate )");
    }

    if (query.getTaskType() != null) {
        if (StringUtils.equals(query.getTaskType(), "running")) {
            buffer.append(" and ti.end is null ");
        } else if (StringUtils.equals(query.getTaskType(), "finished")) {
            buffer.append(" and ti.end is not null ");
        }
    }

    if (query.getProcessName() != null) {
        params.put("processName", query.getProcessName());
        buffer.append(" and ti.processInstance.name = :processName ");
    }

    if (query.getProcessNames() != null && !query.getProcessNames().isEmpty()) {
        Collection<String> collection = query.getProcessNames();
        if (collection != null && collection.size() > 0) {
            buffer.append(" and ( ");
            int index = 0;
            for (Object object : collection) {
                if (index > 0) {
                    buffer.append(" or ");
                }
                String p_name = "processName_" + index;
                buffer.append(" ti.processInstance.processDefinition.name = :").append(p_name);
                params.put(p_name, object);
                index++;
            }
            buffer.append(" ) ");
        }
    }

    if (query.getProcessDefinitionId() != null) {
        buffer.append(" and ti.processInstance.processDefinition.id = :processDefinitionId ");
        params.put("processDefinitionId", query.getProcessDefinitionId());
    }

    if (LogUtils.isDebug()) {
        logger.debug(buffer.toString());
    }

    Session session = jbpmContext.getSession();
    Query q = session.createQuery(buffer.toString());
    q.setMaxResults(5000);

    if (params != null && params.size() > 0) {
        Set<Entry<String, Object>> entrySet = params.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                q.setParameter(name, value);
            }
        }
    }

    List<?> rows = q.list();
    List<TaskInstance> taskInstances = new java.util.ArrayList<TaskInstance>();
    if (rows != null && rows.size() > 0) {
        Iterator<?> iterator = rows.iterator();
        while (iterator.hasNext()) {
            taskInstances.add((TaskInstance) iterator.next());
        }
    }

    return taskInstances;
}