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.unitime.timetable.util.LookupTables.java

License:Open Source License

/**
 * Executes the query to retrieve instructors
 * @param request/* w ww. j  a v  a2 s. com*/
 * @param clause
 * @throws Exception
 */
private static void getInstructors(HttpServletRequest request, SessionContext context, StringBuffer clause)
        throws Exception {
    String instructorNameFormat = UserProperty.NameFormat.get(context.getUser());

    Long acadSessionId = context.getUser().getCurrentAcademicSessionId();

    StringBuffer query = new StringBuffer();
    query.append("select distinct i from DepartmentalInstructor i ");
    query.append(" where i.department.session.uniqueId = :acadSessionId ");
    query.append(clause);
    query.append(" order by upper(i.lastName), upper(i.firstName) ");

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

    Query q = hibSession.createQuery(query.toString());
    q.setFetchSize(5000);
    q.setCacheable(true);
    q.setLong("acadSessionId", acadSessionId);

    List result = q.list();
    Vector v = new Vector(result.size());
    Vector h = new Vector(result.size());
    for (Iterator i = result.iterator(); i.hasNext();) {
        DepartmentalInstructor di = (DepartmentalInstructor) i.next();
        String name = di.getName(instructorNameFormat);
        v.addElement(new ComboBoxLookup(name, di.getUniqueId().toString()));
        if (di.hasPreferences())
            h.add(di.getUniqueId());
    }

    request.setAttribute(DepartmentalInstructor.INSTR_LIST_ATTR_NAME, v);
    request.setAttribute(DepartmentalInstructor.INSTR_HAS_PREF_ATTR_NAME, h);
}

From source file:org.unitime.timetable.webutil.WebEventTableBuilder.java

License:Open Source License

protected List loadEvents(EventListForm form) {
    boolean conf = (form.getMode() == EventListForm.sModeAllConflictingEvents);

    String query = "select distinct e from Event e inner join e.meetings m where e.class in (";

    if (conf) {// w  w  w  . ja  v a2s  .co  m
        query = "select distinct e from Event e inner join e.meetings m, Meeting mx where "
                + "mx.uniqueId!=m.uniqueId and m.meetingDate=mx.meetingDate and m.startPeriod < mx.stopPeriod and m.stopPeriod > mx.startPeriod and "
                + "m.locationPermanentId = mx.locationPermanentId and e.class in (";
    }

    for (int i = 0; i < form.getEventTypes().length; i++) {
        if (i > 0)
            query += ",";
        switch (form.getEventTypes()[i].intValue()) {
        case Event.sEventTypeClass:
            query += "ClassEvent";
            break;
        case Event.sEventTypeFinalExam:
            query += "FinalExamEvent";
            break;
        case Event.sEventTypeMidtermExam:
            query += "MidtermExamEvent";
            break;
        case Event.sEventTypeCourse:
            query += "CourseEvent";
            break;
        case Event.sEventTypeSpecial:
            query += "SpecialEvent";
            break;
        }
        //query += form.getEventTypes()[i];
    }
    query += ")";

    if (form.getEventNameSubstring() != null && form.getEventNameSubstring().trim().length() > 0) {
        query += " and upper(e.eventName) like :eventNameSubstring";
    }

    if (form.getEventDateFrom() != null && form.getEventDateFrom().trim().length() > 0) {
        query += " and m.meetingDate>=:eventDateFrom";
    }

    if (form.getEventDateTo() != null && form.getEventDateTo().trim().length() > 0) {
        query += " and m.meetingDate<=:eventDateTo";
    }

    if (form.getEventMainContactSubstring() != null
            && form.getEventMainContactSubstring().trim().length() > 0) {
        for (StringTokenizer s = new StringTokenizer(form.getEventMainContactSubstring().trim(), ", "); s
                .hasMoreTokens();) {
            String token = s.nextToken().toUpperCase();
            query += " and (upper(e.mainContact.firstName) like '%" + token
                    + "%' or upper(e.mainContact.middleName) like '%" + token
                    + "%' or upper(e.mainContact.lastName) like '%" + token + "%')";
        }
    }

    switch (form.getMode()) {
    case EventListForm.sModeMyEvents:
        query += " and e.mainContact.externalUniqueId = :userId";
        break;
    case EventListForm.sModeAllApprovedEvents:
        query += " and m.approvedDate is not null";
        break;
    case EventListForm.sModeAllEventsWaitingApproval:
        query += " and m.approvedDate is null";
        break;
    case EventListForm.sModeEvents4Approval:
        query += " and m.approvedDate is null";
        break;
    case EventListForm.sModeAllEvents:
        break;
    }

    if (form.getSponsoringOrganization() != null && form.getSponsoringOrganization() >= 0) {
        query += " and e.sponsoringOrganization.uniqueId=:sponsorOrgId";
    }

    if (form.getStartTime() >= 0) {
        query += " and m.stopPeriod > " + form.getStartTime();
    }

    if (form.getStopTime() >= 0) {
        query += " and m.startPeriod < " + form.getStopTime();
    }

    if (form.isDayMon() || form.isDayTue() || form.isDayWed() || form.isDayThu() || form.isDayFri()
            || form.isDaySat() || form.isDaySun()) {
        String dow = "";
        if (form.isDayMon()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "2";
        }
        if (form.isDayTue()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "3";
        }
        if (form.isDayWed()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "4";
        }
        if (form.isDayThu()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "5";
        }
        if (form.isDayFri()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "6";
        }
        if (form.isDaySat()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "7";
        }
        if (form.isDaySun()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "1";
        }
        if (dow.indexOf(',') >= 0)
            query += " and " + HibernateUtil.dayOfWeek("m.meetingDate") + " in (" + dow + ")";
        else
            query += " and " + HibernateUtil.dayOfWeek("m.meetingDate") + " = " + dow;
    }

    query += " order by e.eventName, e.uniqueId";

    Query hibQuery = new EventDAO().getSession().createQuery(query);
    hibQuery.setFetchSize(getMaxResults() + 1);
    if (form.getMode() != EventListForm.sModeEvents4Approval)
        hibQuery.setMaxResults(getMaxResults() + 1);

    if (form.getEventNameSubstring() != null && form.getEventNameSubstring().trim().length() > 0) {
        hibQuery.setString("eventNameSubstring", "%" + form.getEventNameSubstring().toUpperCase().trim() + "%");
    }

    if (form.getEventDateFrom() != null && form.getEventDateFrom().trim().length() > 0) {
        try {
            hibQuery.setDate("eventDateFrom",
                    new SimpleDateFormat("MM/dd/yyyy").parse(form.getEventDateFrom()));
        } catch (ParseException ex) {
            hibQuery.setDate("eventDateFrom", new Date());
        }
    }

    if (form.getEventDateTo() != null && form.getEventDateTo().trim().length() > 0) {
        try {
            hibQuery.setDate("eventDateTo", new SimpleDateFormat("MM/dd/yyyy").parse(form.getEventDateTo()));
        } catch (ParseException ex) {
            hibQuery.setDate("eventDateTo", new Date());
        }
    }

    if (form.getSponsoringOrganization() != null && form.getSponsoringOrganization() >= 0) {
        hibQuery.setLong("sponsorOrgId", form.getSponsoringOrganization());
    }

    switch (form.getMode()) {
    case EventListForm.sModeMyEvents:
        hibQuery.setString("userId", form.getUserId());
        break;
    case EventListForm.sModeAllApprovedEvents:
    case EventListForm.sModeAllEventsWaitingApproval:
    case EventListForm.sModeEvents4Approval:
        break;
    }

    return hibQuery.setCacheable(true).list();
}

From source file:org.unitime.timetable.webutil.WebEventTableBuilder.java

License:Open Source License

protected List<Meeting> loadMeetings(MeetingListForm form) {
    boolean conf = (form.getMode() == EventListForm.sModeAllConflictingEvents);

    String query = "select m from Event e inner join e.meetings m where e.class in (";

    if (conf) {//  w ww .ja v a  2s .c o m
        query = "select m from Event e inner join e.meetings m, Meeting mx where "
                + "mx.uniqueId!=m.uniqueId and m.meetingDate=mx.meetingDate and m.startPeriod < mx.stopPeriod and m.stopPeriod > mx.startPeriod and "
                + "m.locationPermanentId = mx.locationPermanentId and e.class in (";
    }

    for (int i = 0; i < form.getEventTypes().length; i++) {
        if (i > 0)
            query += ",";
        switch (form.getEventTypes()[i].intValue()) {
        case Event.sEventTypeClass:
            query += "ClassEvent";
            break;
        case Event.sEventTypeFinalExam:
            query += "FinalExamEvent";
            break;
        case Event.sEventTypeMidtermExam:
            query += "MidtermExamEvent";
            break;
        case Event.sEventTypeCourse:
            query += "CourseEvent";
            break;
        case Event.sEventTypeSpecial:
            query += "SpecialEvent";
            break;
        }
        //query += form.getEventTypes()[i];
    }
    query += ")";

    if (form.getEventNameSubstring() != null && form.getEventNameSubstring().trim().length() > 0) {
        query += " and upper(e.eventName) like :eventNameSubstring";
    }

    if (form.getEventDateFrom() != null && form.getEventDateFrom().trim().length() > 0) {
        query += " and m.meetingDate>=:eventDateFrom";
    }

    if (form.getEventDateTo() != null && form.getEventDateTo().trim().length() > 0) {
        query += " and m.meetingDate<=:eventDateTo";
    }

    if (form.getEventMainContactSubstring() != null
            && form.getEventMainContactSubstring().trim().length() > 0) {
        for (StringTokenizer s = new StringTokenizer(form.getEventMainContactSubstring().trim(), ", "); s
                .hasMoreTokens();) {
            String token = s.nextToken().toUpperCase();
            query += " and (upper(e.mainContact.firstName) like '%" + token
                    + "%' or upper(e.mainContact.middleName) like '%" + token
                    + "%' or upper(e.mainContact.lastName) like '%" + token + "%')";
        }
    }

    if (form.getLocation() != null && form.getLocation().trim().length() > 0) {
        query += " and ("
                + "(select count(r) from Room as r where r.permanentId = m.locationPermanentId and upper(r.building.abbreviation) like :bldgSubstr and upper(r.roomNumber) like :roomSubstr) > 0 or "
                + "(select count(nul) from NonUniversityLocation as nul where nul.permanentId = m.locationPermanentId and upper(nul.name) like :nameStr) > 0) ";
    }

    switch (form.getMode()) {
    case EventListForm.sModeMyEvents:
        query += " and e.mainContact.externalUniqueId = :userId";
        break;
    case EventListForm.sModeAllApprovedEvents:
        query += " and m.approvedDate is not null";
        break;
    case EventListForm.sModeAllEventsWaitingApproval:
        query += " and m.approvedDate is null";
        break;
    case EventListForm.sModeEvents4Approval:
        query += " and m.approvedDate is null";
        break;
    case EventListForm.sModeAllEvents:
        break;
    }

    if (form.getSponsoringOrganization() != null && form.getSponsoringOrganization() >= 0) {
        query += " and e.sponsoringOrganization.uniqueId=:sponsorOrgId";
    }

    if (form.getStartTime() >= 0) {
        query += " and m.stopPeriod > " + form.getStartTime();
    }

    if (form.getStopTime() >= 0) {
        query += " and m.startPeriod < " + form.getStopTime();
    }

    if (form.isDayMon() || form.isDayTue() || form.isDayWed() || form.isDayThu() || form.isDayFri()
            || form.isDaySat() || form.isDaySun()) {
        String dow = "";
        if (form.isDayMon()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "2";
        }
        if (form.isDayTue()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "3";
        }
        if (form.isDayWed()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "4";
        }
        if (form.isDayThu()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "5";
        }
        if (form.isDayFri()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "6";
        }
        if (form.isDaySat()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "7";
        }
        if (form.isDaySun()) {
            if (!dow.isEmpty())
                dow += ",";
            dow += "1";
        }
        if (dow.indexOf(',') >= 0)
            query += " and " + HibernateUtil.dayOfWeek("m.meetingDate") + " in (" + dow + ")";
        else
            query += " and " + HibernateUtil.dayOfWeek("m.meetingDate") + " = " + dow;
    }

    Query hibQuery = new EventDAO().getSession().createQuery(query);
    hibQuery.setFetchSize(getMaxResults() + 1);
    if (form.getMode() != EventListForm.sModeEvents4Approval)
        hibQuery.setMaxResults(getMaxResults() + 1);

    if (form.getEventNameSubstring() != null && form.getEventNameSubstring().trim().length() > 0) {
        hibQuery.setString("eventNameSubstring", "%" + form.getEventNameSubstring().toUpperCase().trim() + "%");
    }

    if (form.getEventDateFrom() != null && form.getEventDateFrom().trim().length() > 0) {
        try {
            hibQuery.setDate("eventDateFrom",
                    new SimpleDateFormat("MM/dd/yyyy").parse(form.getEventDateFrom()));
        } catch (ParseException ex) {
            hibQuery.setDate("eventDateFrom", new Date());
        }
    }

    if (form.getEventDateTo() != null && form.getEventDateTo().trim().length() > 0) {
        try {
            hibQuery.setDate("eventDateTo", new SimpleDateFormat("MM/dd/yyyy").parse(form.getEventDateTo()));
        } catch (ParseException ex) {
            hibQuery.setDate("eventDateTo", new Date());
        }
    }

    if (form.getSponsoringOrganization() != null && form.getSponsoringOrganization() >= 0) {
        hibQuery.setLong("sponsorOrgId", form.getSponsoringOrganization());
    }

    if (form.getLocation() != null && form.getLocation().trim().length() > 0) {
        String bldgSubstr = null;
        String roomSubstr = null;
        String nameStr = "%" + form.getLocation().toUpperCase() + "%";
        int indexOfFirstSpace = form.getLocation().indexOf(' ');
        if (indexOfFirstSpace == 0) {
            bldgSubstr = "%";
            roomSubstr = "%" + form.getLocation().substring(0, indexOfFirstSpace).toUpperCase() + "%";
        } else if (indexOfFirstSpace < 0) {
            bldgSubstr = "%" + form.getLocation().toUpperCase() + "%";
            roomSubstr = "%";
        } else {
            bldgSubstr = "%" + form.getLocation().substring(0, indexOfFirstSpace).toUpperCase() + "%";
            if (indexOfFirstSpace == form.getLocation().length() - 1) {
                roomSubstr = "%";
            } else {
                roomSubstr = "%" + form.getLocation()
                        .substring(indexOfFirstSpace + 1, form.getLocation().length()).toUpperCase() + "%";
            }
        }
        hibQuery.setString("bldgSubstr", bldgSubstr);
        hibQuery.setString("roomSubstr", roomSubstr);
        hibQuery.setString("nameStr", nameStr);

    }

    switch (form.getMode()) {
    case EventListForm.sModeMyEvents:
        hibQuery.setString("userId", form.getUserId());
        break;
    case EventListForm.sModeAllApprovedEvents:
    case EventListForm.sModeAllEventsWaitingApproval:
    case EventListForm.sModeEvents4Approval:
        break;
    }

    List meetings = hibQuery.setCacheable(true).list();
    if (form.getMode() == EventListForm.sModeEvents4Approval
            || (form.getLocation() != null && form.getLocation().trim().length() > 0)) {
        for (Iterator it = meetings.iterator(); it.hasNext();) {
            Meeting meeting = (Meeting) it.next();
            if (form.getMode() == EventListForm.sModeEvents4Approval) {
                if (meeting.getApprovedDate() != null || meeting.getLocation() == null || !form
                        .getManagingDepartments().contains(meeting.getLocation().getControllingDepartment())) {
                    it.remove();
                    continue;
                }
            }
            if (meeting.getLocation() == null || !match(form.getLocation(), meeting.getLocation().getLabel())) {
                it.remove();
                continue;
            }
        }
    }

    Comparator<Meeting> cmp = null;
    if (MeetingListForm.sOrderByName.equals(form.getOrderBy())) {
        cmp = new Comparator<Meeting>() {
            public int compare(Meeting m1, Meeting m2) {
                int cmp = m1.getEvent().getEventName().compareToIgnoreCase(m2.getEvent().getEventName());
                if (cmp != 0)
                    return cmp;
                cmp = m1.getEvent().getUniqueId().compareTo(m2.getEvent().getUniqueId());
                if (cmp != 0)
                    return cmp;
                return m1.compareTo(m2);
            }
        };
    } else if (MeetingListForm.sOrderByLocation.equals(form.getOrderBy())) {
        cmp = new Comparator<Meeting>() {
            public int compare(Meeting m1, Meeting m2) {
                String l1 = (m1.getLocation() == null ? "" : m1.getLocation().getLabel());
                String l2 = (m2.getLocation() == null ? "" : m2.getLocation().getLabel());
                int cmp = l1.compareToIgnoreCase(l2);
                if (cmp != 0)
                    return cmp;
                return m1.compareTo(m2);
            }
        };
    } else if (MeetingListForm.sOrderByTime.equals(form.getOrderBy())) {
        cmp = new Comparator<Meeting>() {
            public int compare(Meeting m1, Meeting m2) {
                return m1.compareTo(m2);
            }
        };
    }

    if (cmp != null)
        Collections.sort(meetings, cmp);

    return meetings;
}

From source file:org.workin.persistence.hibernate.v4.dao.Hibernate4DaoSupport.java

License:Apache License

/**
 * @description ??Query//from  www .ja v a  2s  .  c o  m
 * @author <a href="mailto:code727@gmail.com">?</a> 
 * @param query
 */
protected void prepareQuery(Query query) {
    if (this.cacheConfiguration != null) {
        if (this.cacheConfiguration.isCacheQueries()) {
            query.setCacheable(true);
            if (StringUtils.isNotBlank(this.cacheConfiguration.getQueryCacheRegion())) {
                query.setCacheRegion(this.cacheConfiguration.getQueryCacheRegion());
            }
        }

        if (this.cacheConfiguration.getFetchSize() > 0)
            query.setFetchSize(this.cacheConfiguration.getFetchSize());

        if (this.cacheConfiguration.getMaxResults() > 0)
            query.setMaxResults(this.cacheConfiguration.getMaxResults());
    }
}

From source file:org.zanata.dao.HTextFlowTargetStreamingDAO.java

License:Open Source License

/**
 *
 * @return scrollable result set of HTextFlowTarget which has all
 *         fields(locale, textflow, document, document locale, project
 *         iteration and project) eagerly fetched.
 *//*from   w  ww .  jav a2s.  c  o  m*/
public ScrollableResults getAllTargetsWithAllFieldsEagerlyFetched() {
    Query query = getSession().createQuery("from HTextFlowTarget tft " + "join fetch tft.locale "
            + "join fetch tft.textFlow " + "join fetch tft.textFlow.document "
            + "join fetch tft.textFlow.document.locale " + "join fetch tft.textFlow.document.projectIteration "
            + "join fetch tft.textFlow.document.projectIteration.project");
    query.setFetchSize(Integer.MIN_VALUE);
    return query.scroll(ScrollMode.FORWARD_ONLY);
}

From source file:org.zanata.dao.HTextFlowTargetStreamingDAO.java

License:Open Source License

/**
 *
 * @return scrollable result set of HTextFlowTarget under a project, with
 *         all of its fields(locale, textflow, document, document locale,
 *         project iteration and project) eagerly fetched.
 *///  w w w . j a v a  2  s  .  com
public ScrollableResults getTargetsWithAllFieldsEagerlyFetchedForProject(HProject project) {
    Query query = getSession().createQuery("from HTextFlowTarget tft " + "join fetch tft.locale "
            + "join fetch tft.textFlow " + "join fetch tft.textFlow.document "
            + "join fetch tft.textFlow.document.locale " + "join fetch tft.textFlow.document.projectIteration "
            + "join fetch tft.textFlow.document.projectIteration.project p where p = :project");
    return query.setFetchSize(Integer.MIN_VALUE).setParameter("project", project)
            .scroll(ScrollMode.FORWARD_ONLY);
}

From source file:org.zanata.dao.HTextFlowTargetStreamingDAO.java

License:Open Source License

/**
 *
 * @return scrollable result set of HTextFlowTarget under a project
 *         iteration, with all of its fields(locale, textflow, document,
 *         document locale, project iteration and project) eagerly fetched.
 *//*from www .ja v  a 2s .co  m*/
public ScrollableResults getTargetsWithAllFieldsEagerlyFetchedForProjectIteration(HProjectIteration iteration) {
    Query query = getSession()
            .createQuery("from HTextFlowTarget tft " + "join fetch tft.locale " + "join fetch tft.textFlow "
                    + "join fetch tft.textFlow.document " + "join fetch tft.textFlow.document.locale "
                    + "join fetch tft.textFlow.document.projectIteration iter "
                    + "join fetch tft.textFlow.document.projectIteration.project where iter = :iteration");
    return query.setFetchSize(Integer.MIN_VALUE).setParameter("iteration", iteration)
            .scroll(ScrollMode.FORWARD_ONLY);
}

From source file:org.zanata.search.HTextFlowTargetIndexingStrategy.java

License:Open Source License

@Override
protected ScrollableResults queryResults(int ignoredOffset, FullTextSession session) {
    // TODO move this query into something like HTextFlowTargetStreamingDAO
    Query query = session.createQuery("from HTextFlowTarget tft " + "join fetch tft.locale "
            + "join fetch tft.textFlow " + "join fetch tft.textFlow.document "
            + "join fetch tft.textFlow.document.locale " + "join fetch tft.textFlow.document.projectIteration "
            + "join fetch tft.textFlow.document.projectIteration.project");
    query.setFetchSize(Integer.MIN_VALUE);
    return query.scroll(ScrollMode.FORWARD_ONLY);
}

From source file:ubic.gemma.persistence.service.association.Gene2GOAssociationDaoImpl.java

License:Apache License

private Map<? extends Gene, ? extends Collection<Characteristic>> fetchBatch(Set<Gene> batch) {
    Map<Long, Gene> giMap = EntityUtils.getIdMap(batch);
    //language=HQL
    final String queryString = "select g.id, geneAss.ontologyEntry from Gene2GOAssociationImpl as geneAss join geneAss.gene g where g.id in (:genes)";
    Map<Gene, Collection<Characteristic>> results = new HashMap<>();
    Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(queryString);
    query.setFetchSize(batch.size());
    query.setParameterList("genes", giMap.keySet());
    List<?> o = query.list();

    for (Object object : o) {
        Object[] oa = (Object[]) object;
        Long g = (Long) oa[0];
        Characteristic vc = (Characteristic) oa[1];
        Gene gene = giMap.get(g);//from  w w  w .ja v a  2s . c  o  m
        assert gene != null;
        if (!results.containsKey(gene)) {
            results.put(gene, new HashSet<Characteristic>());
        }
        results.get(gene).add(vc);
    }

    return results;
}