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

The following examples show how to use org.hibernate.Query#setCacheable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimetableGridSolutionHelper.java    From unitime with Apache License 2.0 6 votes vote down vote up
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 2
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 3
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: TypeManagerImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * @see org.sakaiproject.service.common.type.TypeManager#getType(java.lang.String)
 */
public Type getType(final String uuid)
{
	if (log.isDebugEnabled())
	{
		log.debug("getType(String " + uuid + ")");
	}
	if (uuid == null || uuid.length() < 1)
	{
		throw new IllegalArgumentException("uuid");
	}

	final HibernateCallback hcb = new HibernateCallback()
	{
		public Object doInHibernate(Session session) throws HibernateException
		{
			Query q = session.getNamedQuery(FINDTYPEBYUUID);
			q.setString(UUID, uuid);
			q.setCacheable(cacheFindTypeByUuid);
			q.setCacheRegion(Type.class.getCanonicalName());
			return q.uniqueResult();
		}
	};
	Type type = (Type) getHibernateTemplate().execute(hcb);
	return type;
}
 
Example 5
Source File: ChangeLog.java    From unitime with Apache License 2.0 6 votes vote down vote up
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 6
Source File: MessageForumsForumManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<Attachment> getTopicAttachments(final Long topicId) {
	if (topicId == null) {
		throw new IllegalArgumentException("Null Argument topicId");
	}
	HibernateCallback<List<Attachment>> hcb = session -> {
        Query q = session.getNamedQuery("findTopicAttachments");
        q.setCacheable(true);
        q.setLong("topic", topicId);
        return q.list();
    };
	return getHibernateTemplate().execute(hcb);
}
 
Example 7
Source File: TypeFacadeQueries.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This method return a List of TypeD from DB or cache (Hibernate decides)
 * with the specified authority & domain
 * @param authority
 * @param domain
 * @return List
 */
public List getListByAuthorityDomain(final String authority, final String domain) {
    HibernateCallback<List> hcb = session -> {
        Query q = session.createQuery("from TypeD as t where t.authority = :auth and t.domain = :domain");
        q.setString("auth", authority);
        q.setString("domain", domain);
        q.setCacheable(true);
        return q.list();
    };
    return getHibernateTemplate().execute(hcb);
}
 
Example 8
Source File: QueryCachingDemo.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
public Project getProject(long id) {
	final Session s = openSession();
	s.getTransaction().begin();
	final Query q = s.createQuery( "FROM Project WHERE id = :id" );
	q.setParameter( "id", id );
	q.setCacheable( true );
	final Project project = (Project) q.uniqueResult();
	s.getTransaction().commit();
	return project;
}
 
Example 9
Source File: TransactionalTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemTransactional) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemTransactional) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example 10
Source File: Finder.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
public Query createQuery(Session s) {
	Query query = setParamsToQuery(s.createQuery(getOrigHql()));
	if (getFirstResult() > 0) {
		query.setFirstResult(getFirstResult());
	}
	if (getMaxResults() > 0) {
		query.setMaxResults(getMaxResults());
	}
	if (isCacheable()) {
		query.setCacheable(true);
	}
	return query;
}
 
Example 11
Source File: CmsSiteFlowDaoImpl.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
public CmsSiteFlow findUniqueByProperties(Integer siteId, String accessDate,
		String sessionId, String accessPage) {
	String hql = "from CmsSiteFlow bean where bean.site.id=:siteId and bean.accessDate=:accessDate and bean.sessionId=:sessionId and bean.accessPage=:accessPage";
	Query query = getSession().createQuery(hql);
	query.setParameter("siteId", siteId);
	query.setParameter("accessDate", accessDate);
	query.setParameter("sessionId", sessionId);
	query.setParameter("accessPage", accessPage);
	query.setMaxResults(1);
	query.setCacheable(true);
	return (CmsSiteFlow) query.uniqueResult();
}
 
Example 12
Source File: AbstractSessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void initQuery(Query query, NamedQueryDefinition nqd) {
	query.setCacheable( nqd.isCacheable() );
	query.setCacheRegion( nqd.getCacheRegion() );
	if ( nqd.getTimeout()!=null ) query.setTimeout( nqd.getTimeout().intValue() );
	if ( nqd.getFetchSize()!=null ) query.setFetchSize( nqd.getFetchSize().intValue() );
	if ( nqd.getCacheMode() != null ) query.setCacheMode( nqd.getCacheMode() );
	query.setReadOnly( nqd.isReadOnly() );
	if ( nqd.getComment() != null ) query.setComment( nqd.getComment() );
}
 
Example 13
Source File: EmpDaoImpl.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
public List<Employee> getEmpByName(String ename) {
    Session session = sessionFactory.openSession();
    Query query = session.createQuery("from Employee e where e.ename=:ename");
    query.setParameter("ename", ename);
    query.setCacheable(true);
    List<Employee> employees =  query.list();
    session.close();
    return employees;
}
 
Example 14
Source File: SakaiPersonManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#findSakaiPerson(java.lang.String, org.sakaiproject.api.common.type.Type)
 */
public SakaiPerson getSakaiPerson(final String agentUuid, final Type recordType)
{
	if (log.isDebugEnabled())
	{
		log.debug("getSakaiPerson(String {}, Type {})", agentUuid, recordType);
	}
	if (agentUuid == null || agentUuid.length() < 1) throw new IllegalArgumentException("Illegal agentUuid argument passed!");
	if (recordType == null || !isSupportedType(recordType))
		throw new IllegalArgumentException("Illegal recordType argument passed!");

	final HibernateCallback hcb = new HibernateCallback()
	{
		public Object doInHibernate(Session session) throws HibernateException
		{
			Query q = session.getNamedQuery(HQL_FIND_SAKAI_PERSON_BY_AGENT_AND_TYPE);
			q.setParameter(AGENT_UUID, agentUuid, StringType.INSTANCE);
			q.setParameter(TYPE_UUID, recordType.getUuid(), StringType.INSTANCE);
			q.setCacheable(true);
			return q.uniqueResult();
		}
	};

	log.debug("return (SakaiPerson) getHibernateTemplate().execute(hcb);");
	SakaiPerson sp =  (SakaiPerson) getHibernateTemplate().execute(hcb);
	if (photoService.overRidesDefault() && sp != null && sp.getTypeUuid().equals(this.getSystemMutableType().getUuid())) {
		sp.setJpegPhoto(photoService.getPhotoAsByteArray(sp.getAgentUuid()));
	} 
	
	return sp;
}
 
Example 15
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemReadWrite item = new ItemReadWrite("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemReadWrite) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemReadWrite) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example 16
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemReadWrite item = new ItemReadWrite("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemReadWrite) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemReadWrite) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example 17
Source File: QuestionPoolFacadeQueries.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Integer getCountItemFacades(final Long questionPoolId) {
    final HibernateCallback<Number> hcb = session -> {
        Query q = session.createQuery("select count(ab) from ItemData ab, QuestionPoolItemData qpi where ab.itemId = qpi.itemId and qpi.questionPoolId = :id");
        q.setLong("id", questionPoolId);
        q.setCacheable(true);
        return (Number) q.uniqueResult();
    };
 	    
 return getHibernateTemplate().execute(hcb).intValue();
}
 
Example 18
Source File: TimetableGridSolutionHelper.java    From unitime with Apache License 2.0 4 votes vote down vote up
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 19
Source File: SQLFunctionsInterSystemsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testCachedQueryRegion() throws Exception {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Simple simple = new Simple();
	simple.setName("Simple 1");
	s.save( simple, new Long(10) );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	Query q = s.createQuery("from Simple s where s.name=?");
	q.setCacheRegion("foo");
	q.setCacheable(true);
	q.setString(0, "Simple 1");
	assertTrue( q.list().size()==1 );
	assertTrue( q.list().size()==1 );
	assertTrue( q.list().size()==1 );
	q = s.createQuery("from Simple s where s.name=:name");
	q.setCacheRegion("foo");
	q.setCacheable(true);
	q.setString("name", "Simple 1");
	assertTrue( q.list().size()==1 );
	simple = (Simple) q.list().get(0);

	q.setString("name", "Simple 2");
	assertTrue( q.list().size()==0 );
	assertTrue( q.list().size()==0 );
	simple.setName("Simple 2");
	assertTrue( q.list().size()==1 );
	assertTrue( q.list().size()==1 );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	s.update( simple, new Long(10) );
	s.delete(simple);
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	q = s.createQuery("from Simple s where s.name=?");
	q.setCacheRegion("foo");
	q.setCacheable(true);
	q.setString(0, "Simple 1");
	assertTrue( q.list().size()==0 );
	assertTrue( q.list().size()==0 );
	t.commit();
	s.close();
}
 
Example 20
Source File: InstructionalOffering.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
 * Search for instructional offerings
 * @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){
		if (courseNbr.indexOf('*') >= 0) {
			query.append(" and co.courseNbr like :courseNbr ");
		} else {
			query.append(" and co.courseNbr = :courseNbr ");
		}
	}

	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());
	if (courseNbr != null && courseNbr.length() > 0) {
		if (ApplicationProperty.CourseOfferingNumberUpperCase.isTrue())
           	courseNbr = courseNbr.toUpperCase();
		q.setString("courseNbr", courseNbr.replace('*', '%'));
	}
	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;
}