Example usage for org.hibernate Query setFetchSize

List of usage examples for org.hibernate Query setFetchSize

Introduction

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

Prototype

Query<R> setFetchSize(int fetchSize);

Source Link

Document

Sets a JDBC fetch size hint for the query.

Usage

From source file:org.springframework.batch.item.database.HibernateItemReaderHelper.java

License:Apache License

/**
 * Get a cursor over all of the results, with the forward-only flag set.
 *
 * @param fetchSize the fetch size to use retrieving the results
 * @param parameterValues the parameter values to use (or null if none).
 *
 * @return a forward-only {@link ScrollableResults}
 *///from ww  w  .j a  va2  s  .c  o  m
public ScrollableResults getForwardOnlyCursor(int fetchSize, Map<String, Object> parameterValues) {
    Query query = createQuery();
    if (parameterValues != null) {
        query.setProperties(parameterValues);
    }
    return query.setFetchSize(fetchSize).scroll(ScrollMode.FORWARD_ONLY);
}

From source file:org.springframework.batch.item.database.HibernateItemReaderHelper.java

License:Apache License

/**
 * Read a page of data, clearing the existing session (if necessary) first,
 * and creating a new session before executing the query.
 *
 * @param page the page to read (starting at 0)
 * @param pageSize the size of the page or maximum number of items to read
 * @param fetchSize the fetch size to use
 * @param parameterValues the parameter values to use (if any, otherwise
 * null)/*from   ww w . j  a  va  2 s.c o m*/
 * @return a collection of items
 */
public Collection<? extends T> readPage(int page, int pageSize, int fetchSize,
        Map<String, Object> parameterValues) {

    clear();

    Query query = createQuery();
    if (parameterValues != null) {
        query.setProperties(parameterValues);
    }
    @SuppressWarnings("unchecked")
    List<T> result = query.setFetchSize(fetchSize).setFirstResult(page * pageSize).setMaxResults(pageSize)
            .list();
    return result;

}

From source file:org.springframework.orm.hibernate3.HibernateTemplate.java

License:Apache License

/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.//from   w  w  w  . j  av a 2 s.c  o m
 * @param queryObject the Query object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 * @see SessionFactoryUtils#applyTransactionTimeout
 */
protected void prepareQuery(Query queryObject) {
    if (isCacheQueries()) {
        queryObject.setCacheable(true);
        if (getQueryCacheRegion() != null) {
            queryObject.setCacheRegion(getQueryCacheRegion());
        }
    }
    if (getFetchSize() > 0) {
        queryObject.setFetchSize(getFetchSize());
    }
    if (getMaxResults() > 0) {
        queryObject.setMaxResults(getMaxResults());
    }
    SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory());
}

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@Test
public void testExecuteWithFetchSizeAndMaxResults() throws HibernateException {
    Query query1 = mock(Query.class);
    Query query2 = mock(Query.class);
    Criteria criteria = mock(Criteria.class);

    given(session.createQuery("some query")).willReturn(query1);
    given(query1.setFetchSize(10)).willReturn(query1);
    given(query1.setMaxResults(20)).willReturn(query1);
    given(session.getNamedQuery("some query name")).willReturn(query2);
    given(query2.setFetchSize(10)).willReturn(query2);
    given(query2.setMaxResults(20)).willReturn(query2);
    given(session.createCriteria(TestBean.class)).willReturn(criteria);
    given(criteria.setFetchSize(10)).willReturn(criteria);
    given(criteria.setMaxResults(20)).willReturn(criteria);

    hibernateTemplate.setFetchSize(10);/*from   ww w.j  ava2 s. c o  m*/
    hibernateTemplate.setMaxResults(20);
    hibernateTemplate.execute(new HibernateCallback<Object>() {
        @Override
        public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
            sess.createQuery("some query");
            sess.getNamedQuery("some query name");
            sess.createCriteria(TestBean.class);
            return null;
        }
    });

    verify(session).flush();
    verify(session).close();
}

From source file:org.springframework.orm.hibernate4.HibernateTemplate.java

License:Apache License

/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.//www  .  ja  va  2s .  c  o  m
 * @param queryObject the Query object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareQuery(Query queryObject) {
    if (isCacheQueries()) {
        queryObject.setCacheable(true);
        if (getQueryCacheRegion() != null) {
            queryObject.setCacheRegion(getQueryCacheRegion());
        }
    }
    if (getFetchSize() > 0) {
        queryObject.setFetchSize(getFetchSize());
    }
    if (getMaxResults() > 0) {
        queryObject.setMaxResults(getMaxResults());
    }

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
            .getResource(getSessionFactory());
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        queryObject.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}

From source file:org.springframework.orm.hibernate4.HibernateTemplateTests.java

License:Apache License

@Test
public void testExecuteWithFetchSizeAndMaxResults() {
    Query query1 = mock(Query.class);
    Query query2 = mock(Query.class);
    Criteria criteria = mock(Criteria.class);

    given(session.createQuery("some query")).willReturn(query1);
    given(query1.setFetchSize(10)).willReturn(query1);
    given(query1.setMaxResults(20)).willReturn(query1);
    given(session.getNamedQuery("some query name")).willReturn(query2);
    given(query2.setFetchSize(10)).willReturn(query2);
    given(query2.setMaxResults(20)).willReturn(query2);
    given(session.createCriteria(TestBean.class)).willReturn(criteria);
    given(criteria.setFetchSize(10)).willReturn(criteria);
    given(criteria.setMaxResults(20)).willReturn(criteria);

    hibernateTemplate.setFetchSize(10);// w w w  .  j  a  v a  2s.co  m
    hibernateTemplate.setMaxResults(20);
    hibernateTemplate.execute(new HibernateCallback<Object>() {
        @Override
        public Object doInHibernate(Session sess) {
            sess.createQuery("some query");
            sess.getNamedQuery("some query name");
            sess.createCriteria(TestBean.class);
            return null;
        }
    });
}

From source file:org.unitime.timetable.action.ajax.CourseNumSuggestAction.java

License:Open Source License

/**
 * Retrieve Suggestion List of Course Numbers for a given Subject Area
 *///  ww  w . j av a 2 s.  c  om
public Collection getMultipleSuggestionList(HttpServletRequest request, Map map) {

    List result = null;

    // Read form variables -- Classes Schedule Screen
    if (map.get("session") != null && map.get("session") instanceof String && map.get("subjectArea") != null
            && map.get("subjectArea") instanceof String && map.get("courseNumber") != null) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("       and co.subjectArea.subjectAreaAbbreviation = :subjectArea");
        query.append("       and co.courseNbr like :courseNbr ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(map.get("session").toString()));
        q.setString("subjectArea", map.get("subjectArea").toString());
        q.setString("courseNbr", map.get("courseNumber").toString() + "%");

        result = q.list();

        if (result == null)
            result = new ArrayList();

        return result;
    }

    User user = Web.getUser(request.getSession());

    // Security Checks
    if (!Web.isLoggedIn(request.getSession()) || user == null
            || user.getAttribute(Constants.SESSION_ID_ATTR_NAME) == null)
        return new ArrayList();

    // Get Academic Session
    String acadSessionId = user.getAttribute(Constants.SESSION_ID_ATTR_NAME).toString();

    // Read form variables -- Instructional Offerings Screen, Reservations Screen
    if (map.get("subjectAreaId") != null && map.get("courseNbr") != null
            && map.get("subjectAreaId").toString().length() > 0
            && !Constants.ALL_OPTION_VALUE.equals(map.get("subjectAreaId"))) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("        and co.subjectArea.uniqueId = :subjectAreaId ");
        query.append("        and co.courseNbr like :courseNbr ");
        //query.append("        and co.isControl = true ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(acadSessionId));
        q.setInteger("subjectAreaId", Integer.parseInt(map.get("subjectAreaId").toString()));
        q.setString("courseNbr", map.get("courseNbr").toString() + "%");

        result = q.list();
    }

    // Read form variables -- Distribution Preferences Screen
    if (map.get("filterSubjectAreaId") != null
            && !Constants.BLANK_OPTION_VALUE.equals(map.get("filterSubjectAreaId"))
            && !Constants.ALL_OPTION_VALUE.equals(map.get("filterSubjectAreaId"))
            && map.get("filterCourseNbr") != null) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("        and co.subjectArea.uniqueId = :subjectAreaId ");
        query.append("        and co.courseNbr like :courseNbr ");
        query.append("        and co.isControl = true ");
        query.append("        and co.instructionalOffering.notOffered = false ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(acadSessionId));
        q.setInteger("subjectAreaId", Integer.parseInt(map.get("filterSubjectAreaId").toString()));
        q.setString("courseNbr", map.get("filterCourseNbr").toString() + "%");

        result = q.list();
    }

    // Read form variables -- Classes Screen
    if (map.get("subjectAreaIds") != null && map.get("subjectAreaIds") instanceof String
            && map.get("courseNbr") != null) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("        and co.subjectArea.uniqueId = :subjectAreaId");
        query.append("        and co.courseNbr like :courseNbr ");
        query.append("        and co.instructionalOffering.notOffered = false ");
        //query.append("        and co.isControl = true ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(acadSessionId));
        q.setInteger("subjectAreaId", Integer.parseInt(map.get("subjectAreaIds").toString()));
        q.setString("courseNbr", map.get("courseNbr").toString() + "%");

        result = q.list();
    }

    if (result == null)
        result = new ArrayList();

    return result;
}

From source file:org.unitime.timetable.action.ClassSearchAction.java

License:Open Source License

public static Set getClasses(ClassListFormInterface form, ClassAssignmentProxy classAssignmentProxy) {
    org.hibernate.Session hibSession = (new InstructionalOfferingDAO()).getSession();

    boolean doFilterManager = form.getFilterManager() != null && form.getFilterManager().length() > 0;
    Long filterManager = (doFilterManager ? Long.valueOf(form.getFilterManager()) : null);

    boolean fetchStructure = true;
    boolean fetchCredits = false;//form.getCredit().booleanValue();
    boolean fetchInstructors = false;//form.getInstructor().booleanValue();
    boolean fetchPreferences = false;//form.getPreferences().booleanValue() || form.getTimePattern().booleanValue();
    boolean fetchAssignments = false;//(form.getTimetable()!=null && form.getTimetable().booleanValue());

    String[] subjectIds = form.getSubjectAreaIds();
    if (subjectIds != null && subjectIds.length > 0) {
        StringBuffer query = new StringBuffer();
        query.append("select c, co from Class_ as c ");

        if (fetchStructure) {
            query.append("left join fetch c.childClasses as cc ");
            query.append("left join fetch c.schedulingSubpart as ss ");
            query.append("left join fetch ss.childSubparts as css ");
            query.append("left join fetch ss.instrOfferingConfig as ioc ");
            query.append("left join fetch ioc.instructionalOffering as io ");
            query.append("left join fetch io.courseOfferings as cox ");
        }//from  ww  w  .j a v  a2 s  .com

        if (fetchCredits)
            query.append("left join fetch ss.creditConfigs as ssc ");

        if (fetchPreferences || fetchInstructors) {
            query.append("left join fetch c.classInstructors as ci ");
            query.append("left join fetch ci.instructor as di ");
        }

        if (fetchAssignments) {
            query.append("left join fetch c.assignments as ca ");
            query.append("left join fetch ca.rooms as car ");
        }

        if (fetchPreferences) {
            query.append("left join fetch c.preferences as cp ");
            query.append("left join fetch ss.preferences as ssp ");
            query.append("left join fetch di.preferences as dip ");
        }

        query.append(
                "inner join c.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as co ");
        query.append(" where co.subjectArea.uniqueId in ( ");
        boolean first = true;
        for (int i = 0; i < subjectIds.length; i++) {
            if (!first) {
                query.append(", ");
            } else {
                first = false;
            }
            query.append(subjectIds[i]);
        }
        query.append(") ");
        if (form.getCourseNbr() != null && form.getCourseNbr().length() > 0) {
            String courseNbr = form.getCourseNbr();
            query.append(" and co.courseNbr ");
            if (courseNbr.indexOf('*') >= 0) {
                query.append(" like '");
                courseNbr = courseNbr.replace('*', '%');
            } else {
                query.append(" = '");
            }
            if (ApplicationProperty.CourseOfferingNumberUpperCase.isTrue())
                courseNbr = courseNbr.toUpperCase();
            query.append(courseNbr);
            query.append("'  ");
        }

        if (doFilterManager) {
            if (filterManager.longValue() < 0) { //all departmental
                query.append(" and (c.managingDept is null or c.managingDept in co.subjectArea.department)");
            } else {
                query.append(" and c.managingDept = " + filterManager);
            }
        }

        if (!form.getShowCrossListedClasses()) {
            query.append(" and co.isControl = true ");
        }
        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(1000);
        q.setCacheable(true);
        TreeSet ts = new TreeSet(new ClassCourseComparator(form.getSortBy(), classAssignmentProxy,
                form.getSortByKeepSubparts()));
        long sTime = new java.util.Date().getTime();

        boolean doFilterInstructor = form.getFilterInstructor() != null
                && form.getFilterInstructor().length() > 0;
        String filterInstructor = (doFilterInstructor ? form.getFilterInstructor().toUpperCase() : null);

        boolean doFilterAssignedRoom = form.getFilterAssignedRoom() != null
                && form.getFilterAssignedRoom().length() > 0;
        String filterAssignedRoom = (doFilterAssignedRoom ? form.getFilterAssignedRoom().toUpperCase() : null);

        boolean doFilterIType = form.getFilterIType() != null && form.getFilterIType().length() > 0;
        Integer filterIType = (doFilterIType ? Integer.valueOf(form.getFilterIType()) : null);

        boolean doFilterAssignedTime = ((form.getFilterDayCode() >= 0 && form.getFilterStartSlot() >= 0
                && form.getFilterLength() >= 0)
                || (form.getFilterDayCode() > 0 && form.getFilterStartSlot() < 0
                        && form.getFilterLength() <= 0));
        TimeLocation filterAssignedTime = (doFilterAssignedTime
                ? new TimeLocation((form.getFilterDayCode() == 0 ? 255 : form.getFilterDayCode()),
                        (form.getFilterStartSlot() < 0 ? 0 : form.getFilterStartSlot()),
                        (form.getFilterStartSlot() < 0 ? Constants.SLOTS_PER_DAY
                                : Math.max(5, Constants.SLOT_LENGTH_MIN + form.getFilterLength() - 1)
                                        / Constants.SLOT_LENGTH_MIN),
                        0, 0, null, null, null, 0)
                : null);
        // days, start time & length selected -> create appropriate time location
        // days, start time selected -> create appropriate time location with 1 slot length
        // start time & length selected -> create time location all days with given start time and length
        // only start time selected -> create time location all days with given start time and 1 slot length
        // only days selected -> create time location of given days all day long (all location assigned in the given days overlap)

        Debug.debug(" --- Filter classes ---");
        for (Iterator i = q.list().iterator(); i.hasNext();) {
            Object[] o = (Object[]) i.next();
            Class_ c = (Class_) o[0];
            if (doFilterInstructor) {
                boolean filterLine = true;
                for (Iterator j = c.getClassInstructors().iterator(); j.hasNext();) {
                    ClassInstructor ci = (ClassInstructor) j.next();
                    StringTokenizer stk = new StringTokenizer(filterInstructor, " ,");
                    boolean containsInstructor = true;
                    while (stk.hasMoreTokens()) {
                        String token = stk.nextToken();
                        boolean containsToken = false;
                        if (ci.getInstructor().getFirstName() != null
                                && ci.getInstructor().getFirstName().toUpperCase().indexOf(token) >= 0)
                            containsToken = true;
                        if (!containsToken && ci.getInstructor().getMiddleName() != null
                                && ci.getInstructor().getMiddleName().toUpperCase().indexOf(token) >= 0)
                            containsToken = true;
                        if (!containsToken && ci.getInstructor().getLastName() != null
                                && ci.getInstructor().getLastName().toUpperCase().indexOf(token) >= 0)
                            containsToken = true;
                        if (!containsToken) {
                            containsInstructor = false;
                            break;
                        }
                    }
                    if (containsInstructor) {
                        filterLine = false;
                        break;
                    }
                }
                if (filterLine) {
                    continue;
                }
            }

            if (doFilterIType) {
                ItypeDesc itype = c.getSchedulingSubpart().getItype();
                boolean match = false;
                while (!match && itype != null) {
                    match = itype.getItype().equals(filterIType);
                    itype = itype.getParent();
                }
                if (!match) {
                    continue;
                }
            }

            if (doFilterAssignedTime) {
                try {
                    Assignment a = classAssignmentProxy.getAssignment(c);
                    if (a == null) {
                        continue;
                    }
                    Placement p = a.getPlacement();
                    if (p == null) {
                        continue;
                    }
                    TimeLocation t = p.getTimeLocation();
                    if (t == null) {
                        continue;
                    }
                    boolean overlap = t.shareDays(filterAssignedTime) && t.shareHours(filterAssignedTime);
                    if (!overlap) {
                        continue;
                    }
                } catch (Exception e) {
                    continue;
                }
            }

            if (doFilterAssignedRoom) {
                try {
                    Assignment a = classAssignmentProxy.getAssignment(c);
                    if (a == null) {
                        continue;
                    }
                    Placement p = a.getPlacement();
                    if (p == null || p.getNrRooms() <= 0) {
                        continue;
                    }
                    boolean filterLine = true;
                    if (p.isMultiRoom()) {
                        for (RoomLocation r : p.getRoomLocations()) {
                            if (r.getName().toUpperCase().indexOf(filterAssignedRoom) >= 0) {
                                filterLine = false;
                                break;
                            }
                        }
                    } else {
                        if (p.getRoomLocation().getName().toUpperCase().indexOf(filterAssignedRoom) >= 0) {
                            filterLine = false;
                        }
                    }
                    if (filterLine) {
                        continue;
                    }
                } catch (Exception e) {
                    continue;
                }
            }

            ts.add(o);
        }

        long eTime = new java.util.Date().getTime();
        Debug.debug("fetch time = " + (eTime - sTime));
        Debug.debug("rows = " + ts.size());
        return (ts);

    } else {
        return (new TreeSet());
    }

}

From source file:org.unitime.timetable.action.DistributionPrefsAction.java

License:Open Source License

/**
 * @param index/* w w w.  ja  v  a 2  s.  c o  m*/
 */
private void setLookupLists(HttpServletRequest request, DistributionPrefsForm frm, Vector subjectAreaList,
        ActionMessages errors) {

    int ct = frm.getSubjectArea().size();
    for (int index = 0; index < ct; index++) {

        String subjectAreaId = frm.getSubjectArea(index);
        String courseNbr = frm.getCourseNbr(index);
        String subpart = frm.getItype(index);
        String classNumber = frm.getClassNumber(index);

        Vector crsNumList = null;
        Vector subpartList = null;
        Vector classNumList = null;

        // Process subject area selection
        if (subjectAreaId != null) {
            if (subjectAreaId.equals(Preference.BLANK_PREF_VALUE)) {
                crsNumList = new Vector();
                subpartList = new Vector();
                classNumList = new Vector();
            } else {

                StringBuffer query = new StringBuffer();
                query.append("select co.uniqueId, co.courseNbr, co.title ");
                query.append("  from InstructionalOffering as io , CourseOffering co ");
                query.append(" where co.subjectArea.uniqueId = :subjectAreaId ");
                query.append("       and io.uniqueId = co.instructionalOffering.uniqueId ");
                query.append("       and io.notOffered = false ");
                query.append("       and co.isControl = true ");
                query.append(" order by co.courseNbr ");

                InstructionalOfferingDAO idao = new InstructionalOfferingDAO();
                org.hibernate.Session hibSession = idao.getSession();

                Query q = hibSession.createQuery(query.toString());
                q.setFetchSize(200);
                q.setCacheable(true);
                q.setLong("subjectAreaId", Long.parseLong(subjectAreaId));

                List result = q.list();
                crsNumList = new Vector();
                if (result.size() > 0) {
                    for (int i = 0; i < result.size(); i++) {
                        Object[] a = (Object[]) result.get(i);
                        ComboBoxLookup cbl = new ComboBoxLookup(
                                (a[1].toString() + " - " + (a[2] == null ? "" : a[2].toString())),
                                a[0].toString());
                        crsNumList.addElement(cbl);
                    }

                    // Only one record - select it to save time and one more click
                    if (result.size() == 1) {
                        ComboBoxLookup cbl = (ComboBoxLookup) crsNumList.elementAt(0);
                        frm.setCourseNbr(index, cbl.getValue());
                        courseNbr = frm.getCourseNbr(index);
                    }
                }

                // Process course number selection
                if (courseNbr.equals(Preference.BLANK_PREF_VALUE)) {
                    subpartList = new Vector();
                    classNumList = new Vector();
                } else {
                    query = new StringBuffer();
                    query.append(" select distinct s ");
                    query.append("   from CourseOffering co, ");
                    query.append("        InstructionalOffering io, ");
                    query.append("        InstrOfferingConfig ioc, ");
                    query.append("        SchedulingSubpart s ");
                    query.append("  where co.uniqueId=:courseNbr ");
                    query.append("    and co.instructionalOffering.uniqueId=io.uniqueId ");
                    query.append("    and ioc.instructionalOffering.uniqueId=io.uniqueId ");
                    query.append("    and s.instrOfferingConfig.uniqueId=ioc.uniqueId ");

                    q = hibSession.createQuery(query.toString());
                    q.setFetchSize(200);
                    q.setCacheable(true);
                    q.setLong("courseNbr", Long.parseLong(courseNbr));

                    result = new Vector(q.list());
                    if (result != null && result.size() > 0) {
                        Collections.sort(result,
                                new SchedulingSubpartComparator(
                                        subjectAreaId == null || subjectAreaId.length() == 0 ? null
                                                : new Long(subjectAreaId)));
                        subpartList = new Vector();
                        for (int i = 0; i < result.size(); i++) {
                            SchedulingSubpart a = (SchedulingSubpart) result.get(i);
                            String ssid = a.getUniqueId().toString();
                            String name = a.getItype().getAbbv();
                            String sufix = a.getSchedulingSubpartSuffix();
                            while (a.getParentSubpart() != null) {
                                name = "&nbsp;&nbsp;&nbsp;&nbsp;" + name;
                                a = a.getParentSubpart();
                            }
                            if (a.getInstrOfferingConfig().getInstructionalOffering().getInstrOfferingConfigs()
                                    .size() > 1)
                                name += " [" + a.getInstrOfferingConfig().getName() + "]";
                            ComboBoxLookup cbl = new ComboBoxLookup(
                                    name + (sufix == null || sufix.length() == 0 ? "" : " (" + sufix + ")"),
                                    ssid);
                            subpartList.addElement(cbl);
                        }

                        // Only one record - select it to save time and one more click
                        if (result.size() == 1) {
                            ComboBoxLookup cbl = (ComboBoxLookup) subpartList.elementAt(0);
                            frm.setItype(index, cbl.getValue());
                            subpart = frm.getItype(index);
                        }
                    }

                    if (subpartList == null || subpartList.size() == 0) {
                        subpartList = new Vector();
                        errors.add("classes",
                                new ActionMessage("errors.generic", "No subparts exist for the given course"));
                    }

                    // Process subpart selection
                    if (subpart.equals(Preference.BLANK_PREF_VALUE)) {
                        classNumList = new Vector();
                    } else {
                        query = new StringBuffer();
                        query.append(" select distinct c ");
                        query.append("   from SchedulingSubpart s, ");
                        query.append("        Class_ c ");
                        query.append("  where s.uniqueId=:itype ");
                        query.append("    and s.uniqueId=c.schedulingSubpart.uniqueId ");

                        q = hibSession.createQuery(query.toString());
                        q.setFetchSize(200);
                        q.setCacheable(true);
                        q.setLong("itype", Long.parseLong(subpart));

                        result = q.list();
                        if (result != null && result.size() > 0) {
                            Collections.sort(result, new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY));

                            if (classNumber.equals(Preference.BLANK_PREF_VALUE))
                                frm.setClassNumber(index, DistributionPrefsForm.ALL_CLASSES_SELECT);

                            classNumList = new Vector();
                            for (int i = 0; i < result.size(); i++) {
                                Class_ clazz = (Class_) result.get(i);
                                ComboBoxLookup cbl = new ComboBoxLookup(clazz.getSectionNumberString(),
                                        clazz.getUniqueId().toString());
                                classNumList.addElement(cbl);
                            }
                        } else {
                            classNumList = new Vector();
                            errors.add("classes", new ActionMessage("errors.generic",
                                    "No classes exist for the given subpart"));
                        }
                    }
                }
            }
        }

        // Set drop down lists for a row
        request.setAttribute(DistributionPrefsForm.SUBJ_AREA_ATTR_LIST + index, subjectAreaList);
        request.setAttribute(DistributionPrefsForm.CRS_NUM_ATTR_LIST + index, crsNumList);
        request.setAttribute(DistributionPrefsForm.ITYPE_ATTR_LIST + index, subpartList);
        request.setAttribute(DistributionPrefsForm.CLASS_NUM_ATTR_LIST + index, classNumList);
    }

    saveErrors(request, errors);
}

From source file:org.unitime.timetable.model.InstructionalOffering.java

License:Open Source License

/**
 * Search for instructional offerings/*  w w w . jav  a  2s.c  om*/
 * @param acadSessionId Academic Session
 * @param subjectAreaId Subject Area
 * @param courseNbr Course Number
 * @return TreeSet of results
 */
public static TreeSet<InstructionalOffering> search(Long acadSessionId, Long subjectAreaId, String courseNbr,
        boolean fetchStructure, boolean fetchCredits, boolean fetchInstructors, boolean fetchPreferences,
        boolean fetchAssignments, boolean fetchReservations) {

    org.hibernate.Session hibSession = (new InstructionalOfferingDAO()).getSession();

    StringBuffer query = new StringBuffer();
    query.append("select distinct io ");
    query.append(" from InstructionalOffering as io inner join io.courseOfferings as co ");

    if (fetchStructure) {
        query.append("left join fetch io.courseOfferings as cox ");
        query.append("left join fetch io.instrOfferingConfigs as ioc ");
        query.append("left join fetch ioc.schedulingSubparts as ss ");
        query.append("left join fetch ss.classes as c ");
        query.append("left join fetch ss.childSubparts as css ");
        query.append("left join fetch c.childClasses as cc ");
    }

    if (fetchCredits)
        query.append("left join fetch ss.creditConfigs as ssc ");

    if (fetchPreferences || fetchInstructors) {
        query.append("left join fetch c.classInstructors as ci ");
        query.append("left join fetch ci.instructor as di ");
    }

    if (fetchAssignments) {
        query.append("left join fetch c.assignments as ca ");
        query.append("left join fetch ca.rooms as car ");
    }

    if (fetchPreferences) {
        query.append("left join fetch c.preferences as cp ");
        query.append("left join fetch ss.preferences as ssp ");
        query.append("left join fetch di.preferences as dip ");
    }

    if (fetchReservations) {
        query.append("left join fetch ioc.individualReservations as ir ");
        query.append("left join fetch ioc.studentGroupReservations as sgr ");
        query.append("left join fetch ioc.acadAreaReservations as aar ");
        query.append("left join fetch ioc.posReservations as pr ");
    }

    query.append(" where io.session.uniqueId=:sessionId ");

    if (courseNbr != null && courseNbr.length() > 0) {
        query.append(" and co.courseNbr ");
        if (courseNbr.indexOf('*') >= 0) {
            query.append(" like '");
            courseNbr = courseNbr.replace('*', '%');
        } else {
            query.append(" = '");
        }
        if (ApplicationProperty.CourseOfferingNumberUpperCase.isTrue())
            courseNbr = courseNbr.toUpperCase();
        query.append(courseNbr);
        query.append("'  ");
    }

    query.append(" and co.subjectArea.uniqueId = :subjectAreaId ");

    Query q = hibSession.createQuery(query.toString());
    q.setFetchSize(1000);
    q.setLong("subjectAreaId", subjectAreaId);
    q.setLong("sessionId", acadSessionId.longValue());
    q.setCacheable(true);

    TreeSet<InstructionalOffering> ts = new TreeSet<InstructionalOffering>(
            new InstructionalOfferingComparator(Long.valueOf(subjectAreaId)));

    long sTime = new java.util.Date().getTime();
    ts.addAll(q.list());
    long eTime = new java.util.Date().getTime();
    Debug.debug("fetch time = " + (eTime - sTime));

    return ts;
}