Java Code Examples for org.hibernate.Query.setCacheable()

The following are Jave code examples for showing how to use setCacheable() of the org.hibernate.Query class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: unitimes   File: ChangeLog.java   Source Code and License Vote up 7 votes
public static List findLastNChanges(Long sessionId, Long managerId, Long subjAreaId, Long departmentId, int n) {
    try {
        org.hibernate.Session hibSession = new ChangeLogDAO().getSession(); 
        Query q = hibSession.createQuery(
                    "select ch from ChangeLog ch where " +
                    "ch.session.uniqueId=:sessionId " +
                    (managerId==null?"":"and ch.manager.uniqueId=:managerId ") +
                    (subjAreaId==null?"":"and ch.subjectArea.uniqueId=:subjAreaId ") +
                    (departmentId==null?"":"and ch.department.uniqueId=:departmentId ") + 
                    "order by ch.timeStamp desc");
        q.setLong("sessionId", sessionId.longValue());
        if (managerId!=null) q.setLong("managerId",managerId.longValue());
        if (subjAreaId!=null) q.setLong("subjAreaId",subjAreaId.longValue());
        if (departmentId!=null) q.setLong("departmentId",departmentId.longValue());
        q.setMaxResults(n);
        q.setCacheable(true);
        return q.list();
    } catch (Exception e) {
        Debug.error(e);
    }
    return null;
}
 
Example 2
Project: lams   File: HibernateTemplate.java   Source Code and License Vote up 6 votes
/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.
 * @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());
	}
}
 
Example 3
Project: lams   File: HibernateTemplate.java   Source Code and License Vote up 6 votes
/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.
 * @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());
}
 
Example 4
Project: unitimes   File: TimePattern.java   Source Code and License Vote up 6 votes
public static List<TimePattern> findAll(Long sessionId, Boolean visible) {
	String query = "from TimePattern tp " +
				 	"where tp.session.uniqueId=:sessionId";
	if (visible!=null) 
	    query += " and visible=:visible";
	
	org.hibernate.Session hibSession = new TimePatternDAO().getSession();
	Query q = hibSession.createQuery(query);
	q.setCacheable(true);
	q.setLong("sessionId", sessionId.longValue());
	if (visible!=null) 
	    q.setBoolean("visible", visible.booleanValue());
	
    List<TimePattern> v = q.list();
    Collections.sort(v);
    return v;
}
 
Example 5
Project: unitimes   File: ChangeLog.java   Source Code and License Vote up 6 votes
public static ChangeLog findLastChange(String objectType, Number objectUniqueId, Source source) {
    try {
        org.hibernate.Session hibSession = new ChangeLogDAO().getSession(); 
        Query q = hibSession.createQuery(
                    "select ch from ChangeLog ch " +
                    "where ch.objectUniqueId=:objectUniqueId and ch.objectType=:objectType "+
                    (source==null?"":"and ch.sourceString=:source ") +
                    "and ch.operationString != :note " +
                    "order by ch.timeStamp desc");
        q.setLong("objectUniqueId", objectUniqueId.longValue());
        q.setString("objectType",objectType);
        q.setString("note", Operation.NOTE.toString());
        if (source!=null)
            q.setString("source",source.name());
        q.setMaxResults(1);
        q.setCacheable(true);
        List logs = q.list();
        return (logs.isEmpty()?null:(ChangeLog)logs.get(0));
    } catch (Exception e) {
        Debug.error(e);
    }
    return null;
}
 
Example 6
Project: unitimes   File: ChangeLog.java   Source Code and License Vote up 6 votes
public static List findLastNChanges(Object object, Source source, int n) {
    try {
        Number objectUniqueId = (Number)object.getClass().getMethod("getUniqueId", new Class[]{}).invoke(object, new Object[]{});
        String objectType = object.getClass().getName();
        org.hibernate.Session hibSession = new ChangeLogDAO().getSession(); 
        Query q = hibSession.createQuery(
                    "select ch from ChangeLog ch " +
                    "where ch.objectUniqueId=:objectUniqueId and ch.objectType=:objectType "+
                    (source==null?"":"and ch.sourceString=:source ") +
                    "order by ch.timeStamp desc");
        q.setLong("objectUniqueId", objectUniqueId.longValue());
        q.setString("objectType",objectType);
        if (source!=null)
            q.setString("source",source.name());
        q.setMaxResults(n);
        q.setCacheable(true);
        return q.list();
    } catch (Exception e) {
        Debug.error(e);
    }
    return null;
}
 
Example 7
Project: unitimes   File: TimetableGridSolutionHelper.java   Source Code and License Vote up 6 votes
public static TimetableGridModel createModel(String solutionIdsStr, Department department, org.hibernate.Session hibSession, TimetableGridContext context) {
  	TimetableGridModel model = new TimetableGridModel(ResourceType.DEPARTMENT.ordinal(), department.getUniqueId());
  	model.setName(department.getShortLabel());
  	model.setFirstDay(context.getFirstDay());
  	model.setFirstSessionDay(context.getFirstSessionDay());
  	model.setFirstDate(context.getFirstDate());

  	Query q = hibSession.createQuery("select distinct a from Assignment as a inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as o inner join o.subjectArea.department as d where " +
		"a.solution.uniqueId in ("+solutionIdsStr+") and d.uniqueId=:resourceId and " +
		"o.isControl=true");
q.setCacheable(true);
q.setLong("resourceId", department.getUniqueId());
List assignments = q.list();
createCells(model, assignments, hibSession, context, false);

model.setSize(assignments.size());
model.setUtilization(countUtilization(assignments, context));

return model;
  }
 
Example 8
Project: unitimes   File: TimetableGridSolutionHelper.java   Source Code and License Vote up 6 votes
public static TimetableGridModel createModel(String solutionIdsStr, SubjectArea sa, org.hibernate.Session hibSession, TimetableGridContext context) {
  	TimetableGridModel model = new TimetableGridModel(ResourceType.SUBJECT_AREA.ordinal(), sa.getUniqueId());
  	model.setName(sa.getSubjectAreaAbbreviation());
  	model.setFirstDay(context.getFirstDay());
  	model.setFirstSessionDay(context.getFirstSessionDay());
  	model.setFirstDate(context.getFirstDate());

  	Query q = hibSession.createQuery("select distinct a from Assignment as a inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as o inner join o.subjectArea as sa where " +
		"a.solution.uniqueId in ("+solutionIdsStr+") and sa.uniqueId=:resourceId and " +
		"o.isControl=true");
q.setCacheable(true);
q.setLong("resourceId", sa.getUniqueId());
List assignments = q.list();

createCells(model, assignments, hibSession, context, false);
model.setSize(assignments.size());
model.setUtilization(countUtilization(assignments, context));

return model;
  }
 
Example 9
Project: unitimes   File: TimetableGridSolutionHelper.java   Source Code and License Vote up 6 votes
public static TimetableGridModel createModel(String solutionIdsStr, StudentGroupInfo g, org.hibernate.Session hibSession, TimetableGridContext context) {
  	TimetableGridModel model = new TimetableGridModel(ResourceType.STUDENT_GROUP.ordinal(), g.getGroupId());
  	model.setName(g.getGroupName());
  	model.setFirstDay(context.getFirstDay());
  	model.setFirstSessionDay(context.getFirstSessionDay());
  	model.setFirstDate(context.getFirstDate());

List<Long> classIds = new ArrayList<Long>();
for (StudentGroupInfo.ClassInfo clazz: g.getGroupAssignments())
	classIds.add(clazz.getClassId());
if (classIds.isEmpty()) return null;

Query q = hibSession.createQuery(
		"select distinct a from Assignment a where a.solution.uniqueId in ("+solutionIdsStr+") and a.classId in (:classIds)");
q.setParameterList("classIds", classIds, new LongType());
q.setCacheable(true);
List assignments = q.list();
model.setSize((int)Math.round(g.countStudentWeights()));

for (Iterator i = assignments.iterator(); i.hasNext(); ) {
	Assignment assignment = (Assignment)i.next();
	List<TimetableGridCell> cells = createCells(model, assignment, hibSession, context, false); 
	StudentGroupInfo.ClassInfo ci = g.getGroupAssignment(assignment.getClassId());
	if (ci != null) {
		int total = g.countStudentsOfOffering(assignment.getClazz().getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getUniqueId());
		for (TimetableGridCell cell: cells) {
			cell.setGroup("(" + Math.round(ci.countStudentsWeight()) + ")");
			if (ci.getStudents() != null && !ci.getStudents().isEmpty() && total > 1) {
				int assigned = ci.getStudents().size();
				int minLimit = assignment.getClazz().getExpectedCapacity();
               	int maxLimit = assignment.getClazz().getMaxExpectedCapacity();
               	int limit = maxLimit;
               	if (minLimit < maxLimit) {
               		int roomLimit = (int) Math.floor(assignment.getPlacement().getRoomSize() / (assignment.getClazz().getRoomRatio() == null ? 1.0f : assignment.getClazz().getRoomRatio()));
               		// int roomLimit = Math.round((c.getRoomRatio() == null ? 1.0f : c.getRoomRatio()) * p.getRoomSize());
               		limit = Math.min(Math.max(minLimit, roomLimit), maxLimit);
               	}
                   if (assignment.getClazz().getSchedulingSubpart().getInstrOfferingConfig().isUnlimitedEnrollment() || limit >= 9999) limit = Integer.MAX_VALUE;
				int p = 100 * assigned / Math.min(limit, total);
				cell.setBackground(percentage2color(p));
				cell.setPreference(assigned + " of " + total);
			}
		}
	}
}
model.setUtilization(g.getGroupValue());

return model;
  }
 
Example 10
Project: lams   File: AbstractSessionImpl.java   Source Code and License Vote up 5 votes
private void initQuery(Query query, NamedQueryDefinition nqd) {
	// todo : cacheable and readonly should be Boolean rather than boolean...
	query.setCacheable( nqd.isCacheable() );
	query.setCacheRegion( nqd.getCacheRegion() );
	query.setReadOnly( nqd.isReadOnly() );

	if ( nqd.getTimeout() != null ) {
		query.setTimeout( nqd.getTimeout() );
	}
	if ( nqd.getFetchSize() != null ) {
		query.setFetchSize( nqd.getFetchSize() );
	}
	if ( nqd.getCacheMode() != null ) {
		query.setCacheMode( nqd.getCacheMode() );
	}
	if ( nqd.getComment() != null ) {
		query.setComment( nqd.getComment() );
	}
	if ( nqd.getFirstResult() != null ) {
		query.setFirstResult( nqd.getFirstResult() );
	}
	if ( nqd.getMaxResults() != null ) {
		query.setMaxResults( nqd.getMaxResults() );
	}
	if ( nqd.getFlushMode() != null ) {
		query.setFlushMode( nqd.getFlushMode() );
	}
}
 
Example 11
Project: unitimes   File: SolutionGridModel.java   Source Code and License Vote up 5 votes
public SolutionGridModel(String solutionIdsStr, Department dept, org.hibernate.Session hibSession, TimetableGridContext context) {
	super(sResourceTypeDepartment, dept.getUniqueId().longValue());
	setName(dept.getShortLabel());
	setFirstDay(context.getFirstDay());
	Query q = hibSession.createQuery("select distinct a from Assignment as a inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as o inner join o.subjectArea.department as d where " +
			"a.solution.uniqueId in ("+solutionIdsStr+") and d.uniqueId=:resourceId and " +
			"o.isControl=true");
	q.setCacheable(true);
	q.setLong("resourceId", dept.getUniqueId().longValue());
	List a = q.list();
	setSize(a.size());
	init(a,hibSession,context);
}
 
Example 12
Project: unitimes   File: SolutionGridModel.java   Source Code and License Vote up 5 votes
public SolutionGridModel(String solutionIdsStr, SubjectArea sa, org.hibernate.Session hibSession, TimetableGridContext context) {
	super(sResourceTypeSubjectArea, sa.getUniqueId().longValue());
	setName(sa.getSubjectAreaAbbreviation());
	setFirstDay(context.getFirstDay());
	Query q = hibSession.createQuery("select distinct a from Assignment as a inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as o inner join o.subjectArea as sa where " +
			"a.solution.uniqueId in ("+solutionIdsStr+") and sa.uniqueId=:resourceId and " +
			"o.isControl=true");
	q.setCacheable(true);
	q.setLong("resourceId", sa.getUniqueId().longValue());
	List a = q.list();
	setSize(a.size());
	init(a,hibSession,context);
}
 
Example 13
Project: unitimes   File: Staff.java   Source Code and License Vote up 5 votes
/**
 * 
 * @param deptCode
 * @return
 */
public static List getStaffByDept(String deptCode, Long acadSessionId) throws Exception {	
	if (deptCode == null){
		return(null);
	}
	
	Query q = StaffDAO.getInstance().getSession().createQuery(
			"select distinct s from Staff s where s.dept=:deptCode and " +
			"(select di.externalUniqueId from DepartmentalInstructor di " +
			"where di.department.deptCode=:deptCode and di.department.session.uniqueId=:sessionId and di.externalUniqueId = s.externalUniqueId ) is null");
	q.setString("deptCode", deptCode);
	q.setLong("sessionId", acadSessionId);
	q.setCacheable(true);
	return (q.list());
}
 
Example 14
Project: unitimes   File: LookupTables.java   Source Code and License Vote up 5 votes
/**
   * Executes the query to retrieve instructors
   * @param request
   * @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);
  }
 
Example 15
Project: unitimes   File: SolutionGridModel.java   Source Code and License Vote up 4 votes
public SolutionGridModel(String solutionIdsStr, StudentGroupInfo g, org.hibernate.Session hibSession, TimetableGridContext context) {
	super(sResourceTypeStudentGroup, g.getGroupId());
	setName(g.getGroupName());
	setFirstDay(context.getFirstDay());
	List<Long> classIds = new ArrayList<Long>();
	for (StudentGroupInfo.ClassInfo clazz: g.getGroupAssignments())
		classIds.add(clazz.getClassId());
	if (classIds.isEmpty()) return;
	Query q = hibSession.createQuery(
			"select distinct a from Assignment a where a.solution.uniqueId in ("+solutionIdsStr+") and a.classId in (:classIds)");
	q.setParameterList("classIds", classIds, new LongType());
	q.setCacheable(true);
	List a = q.list();
	setSize((int)Math.round(g.countStudentWeights()));
	for (Iterator i = a.iterator(); i.hasNext(); ) {
		Assignment assignment = (Assignment)i.next();
		TimetableGridCell cell = init(assignment, hibSession, context.getFirstDay(), context.getBgMode());
		StudentGroupInfo.ClassInfo ci = g.getGroupAssignment(assignment.getClassId());
		if (ci != null) {
			int total = g.countStudentsOfOffering(assignment.getClazz().getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering().getUniqueId());
			while (cell != null) {
				cell.setRoomName(cell.getRoomName() + " (" + Math.round(ci.countStudentsWeight()) + ")");
				if (ci.getStudents() != null && !ci.getStudents().isEmpty() && total > 1) {
					int assigned = ci.getStudents().size();
					int minLimit = assignment.getClazz().getExpectedCapacity();
                	int maxLimit = assignment.getClazz().getMaxExpectedCapacity();
                	int limit = maxLimit;
                	if (minLimit < maxLimit) {
                		int roomLimit = (int) Math.floor(assignment.getPlacement().getRoomSize() / (assignment.getClazz().getRoomRatio() == null ? 1.0f : assignment.getClazz().getRoomRatio()));
                		// int roomLimit = Math.round((c.getRoomRatio() == null ? 1.0f : c.getRoomRatio()) * p.getRoomSize());
                		limit = Math.min(Math.max(minLimit, roomLimit), maxLimit);
                	}
                    if (assignment.getClazz().getSchedulingSubpart().getInstrOfferingConfig().isUnlimitedEnrollment() || limit >= 9999) limit = Integer.MAX_VALUE;
					int p = 100 * assigned / Math.min(limit, total);
					cell.setBackground(TimetableGridCell.percentage2color(p));
					cell.setShortComment("<span style='color:rgb(200,200,200)'>" + assigned + " of " + total + "</span>");
					cell.setShortCommentNoColors(assigned + " of " + total);
				}
				cell = cell.getParent();
			}
		}
	}
	setUtilization(g.getGroupValue());
}