@Test public void testSpecificQueryRegionEviction() { int entityCount = 10; insertDummyEntities(entityCount, 0); // miss 1 query list entities Session session = sf.openSession(); Transaction txn = session.beginTransaction(); Query query = session.createQuery("from " + DummyEntity.class.getName()); query.setCacheable(true).setCacheRegion("newregionname"); query.list(); txn.commit(); session.close(); // query is cached // query is invalidated sf.getCache().evictQueryRegion("newregionname"); // miss 1 query session = sf.openSession(); txn = session.beginTransaction(); query = session.createQuery("from " + DummyEntity.class.getName()); query.setCacheable(true); query.list(); txn.commit(); session.close(); assertEquals(0, sf.getStatistics().getQueryCacheHitCount()); assertEquals(2, sf.getStatistics().getQueryCacheMissCount()); }
public void testCachedQuery() 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.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.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(); q = s.createQuery("from Simple s where s.name=:name"); q.setString("name", "Simple 2"); q.setCacheable(true); 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.setCacheable(true); q.setString(0, "Simple 1"); assertTrue(q.list().size() == 0); assertTrue(q.list().size() == 0); t.commit(); s.close(); }
public void testCachedQueryOnInsert() 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"); List list = q.setCacheable(true).list(); assertTrue(list.size() == 1); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); q = s.createQuery("from Simple s"); list = q.setCacheable(true).list(); assertTrue(list.size() == 1); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); Simple simple2 = new Simple(); simple2.setCount(133); s.save(simple2, new Long(12)); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); q = s.createQuery("from Simple s"); list = q.setCacheable(true).list(); assertTrue(list.size() == 2); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); q = s.createQuery("from Simple s"); list = q.setCacheable(true).list(); assertTrue(list.size() == 2); Iterator i = list.iterator(); while (i.hasNext()) s.delete(i.next()); t.commit(); s.close(); }
public Content getSide( Integer id, Integer siteId, Integer channelId, boolean next, boolean cacheable) { Finder f = Finder.create("from Content bean where 1=1"); if (channelId != null) { f.append(" and bean.channel.id=:channelId"); f.setParam("channelId", channelId); } else if (siteId != null) { f.append(" and bean.site.id=:siteId"); f.setParam("siteId", siteId); } if (next) { f.append(" and bean.id>:id"); f.setParam("id", id); f.append(" and bean.status=" + ContentCheck.CHECKED); f.append(" order by bean.id asc"); } else { f.append(" and bean.id<:id"); f.setParam("id", id); f.append(" and bean.status=" + ContentCheck.CHECKED); f.append(" order by bean.id desc"); } Query query = f.createQuery(getSession()); query.setCacheable(cacheable).setMaxResults(1); return (Content) query.uniqueResult(); }
public void getDistPrefsTableAsPdf( OutputStream out, HttpServletRequest request, SessionContext context, Long subjectAreaId, String courseNbr, Long examTypeId) throws Exception { Query q = new DistributionPrefDAO() .getSession() .createQuery( "select distinct dp from DistributionPref dp " + "inner join dp.distributionObjects do, Exam x inner join x.owners o " + "where " + (courseNbr == null || courseNbr.trim().length() == 0 ? "" : courseNbr.indexOf('*') >= 0 ? "o.course.courseNbr like :courseNbr and " : "o.course.courseNbr=:courseNbr and") + (subjectAreaId == null ? "" : " o.course.subjectArea.uniqueId=:subjectAreaId and ") + "dp.distributionType.examPref = true and " + "do.prefGroup = x and x.session.uniqueId=:sessionId and x.examType.uniqueId=:examTypeId") .setLong("sessionId", context.getUser().getCurrentAcademicSessionId()) .setLong("examTypeId", examTypeId); if (subjectAreaId != null) q.setLong("subjectAreaId", subjectAreaId); if (courseNbr != null && courseNbr.trim().length() != 0) q.setString("courseNbr", courseNbr.trim().replaceAll("\\*", "%")); List distPrefs = q.setCacheable(true).list(); toPdfTable(out, request, context, distPrefs, examTypeId); }
/** * for a given locale, we can filter it by content state or search in source and target. * * @param documentId document id (NOT the String type docId) * @param hLocale locale * @param constraints filter constraints * @param firstResult start index * @param maxResult max result * @return a list of HTextFlow that matches the constraint. * @see * org.zanata.service.impl.TextFlowSearchServiceImpl#findTextFlows(org.zanata.webtrans.shared.model.WorkspaceId, * org.zanata.search.FilterConstraints) */ public List<HTextFlow> getTextFlowByDocumentIdWithConstraints( DocumentId documentId, HLocale hLocale, FilterConstraints constraints, int firstResult, int maxResult) { FilterConstraintToQuery constraintToQuery = FilterConstraintToQuery.filterInSingleDocument(constraints, documentId); String queryString = constraintToQuery.toEntityQuery(); log.debug("\n query {}\n", queryString); Query textFlowQuery = getSession().createQuery(queryString); constraintToQuery.setQueryParameters(textFlowQuery, hLocale); textFlowQuery.setFirstResult(firstResult).setMaxResults(maxResult); textFlowQuery .setCacheable(true) .setComment("TextFlowDAO.getTextFlowByDocumentIdWithConstraint"); @SuppressWarnings("unchecked") List<HTextFlow> result = textFlowQuery.list(); log.debug( "{} textFlow for locale {} filter by {}", result.size(), hLocale.getLocaleId(), constraints); return result; }
private <T> List<T> executeQuery( Query query, int numColumns, LastModificationDateFactory<T> lastModificationDateFactory) { query.setReadOnly(true); query.setCacheable(false); ScrollableResults scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY); final List<T> dates = new ArrayList<>(); int resultsCount = 0; int datesCount = 0; while (scrollableResults.next()) { resultsCount++; Object[] row = scrollableResults.get(); T date = extractLastModificationDate(row, numColumns, lastModificationDateFactory); if (date != null) { dates.add(date); datesCount++; } } if (resultsCount > datesCount) { LOGGER.warn( "Got {} in result set and {} dates. query= {}", resultsCount, datesCount, query.getQueryString()); } else { LOGGER.debug("Got {} in result set and {} dates.", resultsCount, datesCount); } return dates; }
public int getTotalBalance(Object holder, boolean useRegion) throws Exception { List results = null; tm.begin(); try { Query query = sessionFactory .getCurrentSession() .createQuery( "select account.balance from Account as account where account.accountHolder = ?"); query.setParameter(0, holder); if (useRegion) { query.setCacheRegion("AccountRegion"); } query.setCacheable(true); results = query.list(); tm.commit(); } catch (Exception e) { log.error("rolling back", e); tm.rollback(); throw e; } int total = 0; if (results != null) { for (Iterator it = results.iterator(); it.hasNext(); ) { total += ((Integer) it.next()).intValue(); System.out.println("Total = " + total); } } return total; }
public int getTotalWords() { Query q = getSession().createQuery("select sum(tf.wordCount) from HTextFlow tf where tf.obsolete=0"); q.setCacheable(true).setComment("TextFlowDAO.getTotalWords"); Long totalCount = (Long) q.uniqueResult(); return totalCount == null ? 0 : totalCount.intValue(); }
/** * execute a <code>hql</code> sentence. * * @param hsql String * @return List or null * @throws HibernateException */ @SuppressWarnings("unchecked") public <T> ArrayList<T> hql(T type, String hql, int maxResults) throws HibernateException { if (hql == null || hql.length() < 1) { throw new IllegalArgumentException("the parameter hql is null"); } if (type == null) { throw new IllegalArgumentException("the parameter type is null"); } ArrayList<T> arrayList = null; Query query = null; try { session.setCacheMode(CacheMode.IGNORE); query = session.createQuery(hql); query.setMaxResults(maxResults); query.setProperties(type); query.setCacheable(false); arrayList = (ArrayList<T>) query.list(); session.flush(); session.clear(); } catch (HibernateException he) { throw he; } finally { HibernateUtil.closeSession(session); type = null; } return arrayList; } // end hql
public Collection<RelatedChildContent> findRelatedChildrenByKeys( List<ContentVersionKey> contentVersionKeys) { if (contentVersionKeys == null || contentVersionKeys.size() == 0) { throw new IllegalArgumentException("Given contentVersionKeys must contain values"); } String hql = getRelatedChildrenByKeyHQL(contentVersionKeys); Query compiled = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql); compiled.setCacheable(true); @SuppressWarnings({"unchecked"}) List<Object[]> list = compiled.list(); List<RelatedChildContent> relatedChildContrents = new ArrayList<RelatedChildContent>(); for (Object[] row : list) { ContentVersionKey versionKey = (ContentVersionKey) row[0]; ContentEntity content = (ContentEntity) row[1]; RelatedChildContent relatedChildContent = new RelatedChildContent(versionKey, content); relatedChildContrents.add(relatedChildContent); } return relatedChildContrents; }
@Override public List<SchoolCoding> getSchool(String province) { // TODO Auto-generated method stub Query query = getSession().createQuery(getSchoolHql); query.setCacheable(true); query.setString("province", province); return query.list(); }
@Override public List<SchoolCoding> getSchoolByProvinceId(Integer provinceId) { // TODO Auto-generated method stub Query query = getSession().createQuery(getSchoolByProvinceIdHql); query.setCacheable(true); query.setInteger("school_pro_id", provinceId); return query.list(); }
protected List<DummyEntity> executeQuery(SessionFactory factory) { Session session = factory.openSession(); try { Query query = session.createQuery("from " + DummyEntity.class.getName()); query.setCacheable(true); return query.list(); } finally { session.close(); } }
public int countActiveTextFlowsInDocument(Long documentId) { Query q = getSession() .createQuery( "select count(*) from HTextFlow tf where tf.obsolete=0 and tf.document.id = :documentId"); q.setParameter("documentId", documentId); q.setCacheable(true).setComment("TextFlowDAO.countActiveTextFlowsInDocument"); Long totalCount = (Long) q.uniqueResult(); return totalCount == null ? 0 : totalCount.intValue(); }
/** 查询全部 (推荐) */ public void list() { SessionFactory sessionFactory = ExampleHibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); String hql = "from Object"; Query query = session.createQuery(hql); query.setCacheable(true); // 设置缓存 List<Object> list = query.list(); show(list); session.close(); }
/** 查询全部 (推荐) */ @Test public void test_list() { SessionFactory sessionFactory = SessionFactoryUtils.getSessionFactory(); Session session = sessionFactory.openSession(); String hql = "from Emp"; Query query = session.createQuery(hql); query.setCacheable(true); // 设置缓存 List<Emp> list = query.list(); show(list); session.close(); }
@SuppressWarnings("unchecked") public List<HTextFlow> findByIdList(List<Long> idList) { if (idList == null || idList.isEmpty()) { return new ArrayList<HTextFlow>(); } Query query = getSession().createQuery("FROM HTextFlow WHERE id in (:idList)"); query.setParameterList("idList", idList); // caching could be expensive for long idLists query.setCacheable(false).setComment("TextFlowDAO.getByIdList"); return query.list(); }
@Override @SuppressWarnings("unchecked") public List<ContentTag> getList(Integer count, boolean cacheable) { String hql = "from ContentTag bean order by bean.count desc"; Query query = getSession().createQuery(hql); if (count != null) { query.setMaxResults(count); } query.setCacheable(cacheable); return query.list(); }
private Query createQuery( String queryString, @Nullable QueryModifiers modifiers, boolean forCount) { Query query = session.createQuery(queryString); HibernateUtil.setConstants(query, getConstants(), getMetadata().getParams()); if (fetchSize > 0) { query.setFetchSize(fetchSize); } if (timeout > 0) { query.setTimeout(timeout); } if (cacheable != null) { query.setCacheable(cacheable); } if (cacheRegion != null) { query.setCacheRegion(cacheRegion); } if (comment != null) { query.setComment(comment); } if (readOnly != null) { query.setReadOnly(readOnly); } for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) { query.setLockMode(entry.getKey().toString(), entry.getValue()); } if (flushMode != null) { query.setFlushMode(flushMode); } if (modifiers != null && modifiers.isRestricting()) { if (modifiers.getLimit() != null) { query.setMaxResults(modifiers.getLimit().intValue()); } if (modifiers.getOffset() != null) { query.setFirstResult(modifiers.getOffset().intValue()); } } // set transformer, if necessary List<? extends Expression<?>> projection = getMetadata().getProjection(); if (projection.size() == 1 && !forCount) { Expression<?> expr = projection.get(0); if (expr instanceof FactoryExpression<?>) { query.setResultTransformer( new FactoryExpressionTransformer((FactoryExpression<?>) projection.get(0))); } } else if (!forCount) { FactoryExpression<?> proj = FactoryExpressionUtils.wrap(projection); if (proj != null) { query.setResultTransformer(new FactoryExpressionTransformer(proj)); } } return query; }
/** * 通过Finder获得记录总数 * * @param finder 条件组装器 * @return 记录数 */ public int countQueryResult(Finder finder) { String hql = finder.getRowCountHql(); Query query = getSession().createQuery(hql); finder.setParamsToQuery(query); if (finder.isCacheable()) { query.setCacheable(true); } return ((Number) query.iterate().next()).intValue(); }
public long countActiveTextFlowsInProjectIteration(Long versionId) { String query = "select count(*) from HTextFlow tf where tf.obsolete = 0 " + "and tf.document.obsolete = 0 " + "and tf.document.projectIteration.id=:versionId"; Query q = getSession().createQuery(query); q.setParameter("versionId", versionId); q.setCacheable(true).setComment("TextFlowDAO.countTextFlowsInProjectIteration"); return (Long) q.uniqueResult(); }
public Object queryUnique(final String queryString, final Object... values) { Query query = getSession().createQuery(queryString); if (cacheRegion.get() != null) { query.setCacheRegion(cacheRegion.get()); query.setCacheable(true); cacheRegion.set(null); } for (int position = 0; position < values.length; position++) { query.setParameter(position, values[position]); } return query.uniqueResult(); }
public Object queryUnique(final String queryString, final Map paraMap) { Query query = getSession().createQuery(queryString); if (cacheRegion.get() != null) { query.setCacheRegion(cacheRegion.get()); query.setCacheable(true); cacheRegion.set(null); } if (paraMap != null) { query.setProperties(paraMap); } return query.uniqueResult(); }
private int doGetNumberOfRelatedParentsByKey(List<ContentKey> contentKeys) { String hql = getNumberOfRelatedParentsByKeyHQL(contentKeys); Query compiled = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql); compiled.setCacheable(true); @SuppressWarnings({"unchecked"}) int count = ((Number) compiled.uniqueResult()).intValue(); return count; }
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; }
@Test public void test() throws InterruptedException { Session session = HibernateUtils.sessionFactory.openSession(); Query query = session.createQuery("select name from Classes"); query.setCacheable(true); query.list(); session.close(); session = HibernateUtils.sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Classes classes = (Classes) session.get(Classes.class, 1L); classes.setName("us"); transaction.commit(); session.close(); session = HibernateUtils.sessionFactory.openSession(); query = session.createQuery("select name from Classes"); query.setCacheable(true); query.list(); session.close(); }
// select * from // ( select e.*, rownum rn from ( select * from obj ) e where rownum <= 10 ) // where rn > 1 public void pagination() { int pageNo = 1; // 当前页数 int pageSize = 5; // 每页显示条数 SessionFactory sessionFactory = ExampleHibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); String hql = "from Object"; Query query = session.createQuery(hql); query.setFirstResult((pageNo - 1) * pageSize); query.setMaxResults(pageSize); query.setCacheable(true); // 设置缓存 List<Object> list = query.list(); show(list); session.close(); }
public List<Object[]> getTextFlowAndTarget(List<Long> idList, Long localeId) { StringBuilder queryBuilder = new StringBuilder(); queryBuilder .append("from HTextFlow tf ") .append("left join tf.targets tft with tft.locale.id =:localeId ") .append("where tf.id in (:idList)"); Query q = getSession().createQuery(queryBuilder.toString()); q.setParameterList("idList", idList); q.setParameter("localeId", localeId); q.setCacheable(true); q.setComment("TextFlowTargetDAO.getTextFlowTarget"); return q.list(); }
// select * from // ( select e.*, rownum rn from ( select * from emp ) e where rownum <= 10 ) // where rn > 1 @Test public void test_pagination() { int pageNo = 1; // 当前页数 int pageSize = 5; // 每页显示条数 SessionFactory sessionFactory = SessionFactoryUtils.getSessionFactory(); Session session = sessionFactory.openSession(); String hql = "from Emp"; Query query = session.createQuery(hql); query.setFirstResult((pageNo - 1) * pageSize); query.setMaxResults(pageSize); query.setCacheable(true); // 设置缓存 List<Emp> list = query.list(); show(list); session.close(); }