List of usage examples for org.hibernate Query setCacheable
Query<R> setCacheable(boolean cacheable);
From source file:com.liusoft.dlog4j.dao.PhotoDAO.java
License:Open Source License
/** * FIXME: photo/show.vm//from ww w . ja va2 s .c o m * * @param site * @param loginUser * @param month * @return */ public static int[] statCalendarPhotoCount(SiteBean site, SessionUserObject user, Calendar month) { Calendar firstDate = (Calendar) month.clone(); firstDate.set(Calendar.DATE, 1); DateUtils.resetTime(firstDate); Calendar nextMonthFirstDate = (Calendar) firstDate.clone(); nextMonthFirstDate.add(Calendar.MONTH, 1); // Calendar tempCal = (Calendar) nextMonthFirstDate.clone(); tempCal.add(Calendar.DATE, -1); int dateCount = tempCal.get(Calendar.DATE); int[] logCounts = new int[dateCount + 1]; // boolean is_owner = site.isOwner(user); StringBuffer hql = new StringBuffer( "SELECT j.createTime FROM PhotoBean AS j WHERE j.createTime>=:beginTime AND j.createTime<:endTime AND j.site.id=:site"); if (!is_owner) { // hql.append(" AND j.status=:status AND j.album.type=:album_type"); } try { Session ssn = getSession(); Query q = ssn.createQuery(hql.toString()); q.setCacheable(true); q.setCacheRegion("query.photo_calendar"); q.setTimestamp("beginTime", firstDate.getTime()); q.setTimestamp("endTime", nextMonthFirstDate.getTime()); q.setInteger("site", site.getId()); if (!is_owner) { q.setInteger("status", PhotoBean.STATUS_NORMAL); q.setInteger("album_type", AlbumBean.TYPE_PUBLIC); } int total = 0; Iterator logs = q.list().iterator(); while (logs.hasNext()) { tempCal.setTime((Date) logs.next()); int date = tempCal.get(Calendar.DATE); logCounts[date]++; total++; } logCounts[0] = total; return logCounts; } finally { hql = null; firstDate = null; nextMonthFirstDate = null; tempCal = null; } }
From source file:com.liusoft.dlog4j.dao.PhotoDAO.java
License:Open Source License
/** * //from w w w. ja v a 2 s . c o m * * @param site * @param user * @param fromIdx * @param count * @return */ public static List listPhotoReplies(SiteBean site, int fromIdx, int count, SessionUserObject user) { boolean is_owner = site.isOwner(user); StringBuffer hql = new StringBuffer( "FROM PhotoReplyBean AS r WHERE r.status=:status AND r.site.id=:site AND r.photo.status=:photo_status"); if (!is_owner) { // hql.append(" AND r.photo.album.type=:album_type"); hql.append(" AND (r.ownerOnly = 0 OR r.user.id=:userid)"); } hql.append(" ORDER BY r.id DESC"); Session ssn = getSession(); Query q = ssn.createQuery(hql.toString()); q.setCacheable(true).setCacheRegion("query.new_replies_of_site"); q.setInteger("status", PhotoReplyBean.STATUS_NORMAL); q.setInteger("photo_status", PhotoBean.STATUS_NORMAL); q.setInteger("site", site.getId()); if (!is_owner) { q.setInteger("album_type", AlbumBean.TYPE_PUBLIC); q.setInteger("userid", (user != null) ? user.getId() : -1); } if (fromIdx > 0) q.setFirstResult(fromIdx); if (count > 0) q.setMaxResults(count); return q.list(); }
From source file:com.liusoft.dlog4j.dao.TagDAO.java
License:Open Source License
/** * /*from ww w.j a v a2 s . co m*/ * * @param site * @param fromIdx * @param count * @return */ public static List listTags(SiteBean site, int fromIdx, int count) { StringBuffer hql = new StringBuffer("SELECT t.name,COUNT(*) FROM TagBean t"); if (site != null) hql.append(" WHERE t.site.id = ?"); hql.append(" GROUP BY t.name ORDER BY 2 DESC"); Query query = getSession().createQuery(hql.toString()); query.setCacheable(true); query.setCacheRegion(CACHE_KEY); if (site != null) query.setInteger(0, site.getId()); if (fromIdx > 0) query.setFirstResult(fromIdx); if (count > 0) query.setMaxResults(count); List<String> tags = new ArrayList<String>(); List results = query.list(); for (int i = 0; results != null && i < results.size(); i++) { tags.add((String) ((Object[]) results.get(i))[0]); } return tags; }
From source file:com.mg.framework.support.orm.OrmTemplateHibernateImpl.java
License:Open Source License
@Override protected void prepareQuery(Query queryObject) { if (isCacheQueries()) { queryObject.setCacheable(true); if (getQueryCacheRegion() != null) { queryObject.setCacheRegion(getQueryCacheRegion()); }//from w w w . j a v a 2 s.c o m } if (getFetchSize() > 0) { queryObject.setFetchSize(getFetchSize()); } if (getMaxResults() > 0) { queryObject.setMaxResults(getMaxResults()); } if (getFlushMode() != null) { queryObject.setFlushMode(CriteriaHibernateImpl.convertFlushModeToHibernate(getFlushMode())); } //SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory()); }
From source file:com.mysema.query.jpa.hibernate.AbstractHibernateQuery.java
License:Apache License
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);// w ww . j ava2 s . co m } 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; }
From source file:com.oracle.coherence.hibernate.cache.CoherenceHibernateSecondLevelCachePerformanceTest.java
License:CDDL license
/** * Measures the latency of a query with Coherence second-level caching. *//*from w ww .ja v a2 s.co m*/ //@Test public void measureQueryLatencyWithCoherenceCaching() throws InterruptedException, IOException { //setup startDatabase(); startCacheServer(CACHE_CONFIG_FILE_PATH); Thread.currentThread().sleep(5 * 1000); joinCluster(CACHE_CONFIG_FILE_PATH); //setup for (int i = 1; i <= 100; i++) createAndStorePerson(); long cumulativeLatency = 0; for (int i = 1; i <= 1000; i++) { Session session = newSession("hibernate.cfg.xml"); session.beginTransaction(); long clockBefore = System.nanoTime(); Query query = session.createQuery("from Person"); query.setCacheable(true); query.list(); cumulativeLatency += System.nanoTime() - clockBefore; session.getTransaction().commit(); session.close(); } System.out.println( "Average Query.list() latency with query caching: " + cumulativeLatency / 1000L + " nanoseconds"); //teardown leaveCluster(); cluster.destroy(); hsqldbProcess.destroy(); //teardown }
From source file:com.oracle.coherence.hibernate.cachestore.HibernateCacheLoader.java
License:CDDL license
/** * Load a collection of Hibernate entities given a set of ids (keys) * * @param keys the cache keys; specifically, the entity ids * * @return the corresponding Hibernate entity instances *//* w w w . j a v a 2 s . c o m*/ public Map loadAll(Collection keys) { ensureInitialized(); Map results = new HashMap(); Transaction tx = null; Session session = openSession(); SessionImplementor sessionImplementor = (SessionImplementor) session; try { tx = session.beginTransaction(); // Create the query String sQuery = getLoadAllQuery(); Query query = session.createQuery(sQuery); // Prevent Hibernate from caching the results query.setCacheMode(CacheMode.IGNORE); query.setCacheable(false); query.setReadOnly(true); // Parameterize the query (where :keys = keys) query.setParameterList(PARAM_IDS, keys); // Need a way to extract the key from an entity that we know // nothing about. ClassMetadata classMetaData = getEntityClassMetadata(); // Iterate through the results and place into the return map for (Iterator iter = query.list().iterator(); iter.hasNext();) { Object entity = iter.next(); Object id = classMetaData.getIdentifier(entity, sessionImplementor); results.put(id, entity); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw ensureRuntimeException(e); } finally { closeSession(session); } return results; }
From source file:com.qcadoo.model.internal.search.SearchQueryImpl.java
License:Open Source License
@Override public void addCacheable(Query query) { query.setCacheable(cacheable); }
From source file:com.querydsl.jpa.hibernate.AbstractHibernateQuery.java
License:Apache License
private Query createQuery(@Nullable QueryModifiers modifiers, boolean forCount) { JPQLSerializer serializer = serialize(forCount); String queryString = serializer.toString(); logQuery(queryString, serializer.getConstantToLabel()); Query query = session.createQuery(queryString); HibernateUtil.setConstants(query, serializer.getConstantToLabel(), getMetadata().getParams()); if (fetchSize > 0) { query.setFetchSize(fetchSize);// w w w . j a v a2s.c om } 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()) { Integer limit = modifiers.getLimitAsInteger(); Integer offset = modifiers.getOffsetAsInteger(); if (limit != null) { query.setMaxResults(limit); } if (offset != null) { query.setFirstResult(offset); } } // set transformer, if necessary Expression<?> projection = getMetadata().getProjection(); if (!forCount && projection instanceof FactoryExpression) { query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection)); } return query; }
From source file:com.quix.aia.cn.imo.mapper.AamDataMaintenance.java
License:Open Source License
/** * <p>/*from www . j a va2 s . c o m*/ * This method retrieves list of data for matching bu, district, city, ssc * </p> * * @param AamData * @param typeOfData * * @return AamData model * */ public static AamData getData(AamData aamData, String typeOfData) { Integer i = 0; String queryStr = ""; Session session = null; Query query = null; Object[] objs; try { session = HibernateFactory.openSession(); if ("office".equalsIgnoreCase(typeOfData)) { queryStr = "SELECT officeCode, officeName FROM Office WHERE officeName = '" + aamData.getOfficeCode() + "' AND status=1 "; } else if ("ssc".equalsIgnoreCase(typeOfData)) { queryStr = "SELECT sscCode, sscName FROM Ssc WHERE sscName = '" + aamData.getSsc() + "' AND status=1"; } else if ("city".equalsIgnoreCase(typeOfData)) { queryStr = "SELECT cityCode, cityName FROM City WHERE cityName = '" + aamData.getCity() + "' AND status=1"; } else if ("branch".equalsIgnoreCase(typeOfData)) { queryStr = "SELECT branchCode, distCode, branchFullName FROM Branch WHERE branchName = '" + aamData.getBranch() + "' AND status=1"; } else if ("district".equalsIgnoreCase(typeOfData)) { queryStr = "SELECT districtName, buCode FROM District WHERE status=1 AND districtCode = " + aamData.getDistrictCode(); } else if ("bu".equalsIgnoreCase(typeOfData)) { queryStr = "SELECT buCode, buName FROM Bu WHERE status=1 AND buCode = " + aamData.getBuCode(); } query = session.createQuery(queryStr); List list = query.setCacheable(true).list(); if (!list.isEmpty()) { objs = (Object[]) list.get(0); if ("office".equalsIgnoreCase(typeOfData)) { aamData.setOfficeCode("" + objs[0]); aamData.setOfficeName("" + objs[1]); } else if ("ssc".equalsIgnoreCase(typeOfData)) { aamData.setSscCode((Integer) objs[0]); aamData.setSsc((String) objs[1]); } else if ("city".equalsIgnoreCase(typeOfData)) { aamData.setCityCode((Integer) objs[0]); aamData.setCity((String) objs[1]); } else if ("branch".equalsIgnoreCase(typeOfData)) { aamData.setBranchCode((Integer) objs[0]); aamData.setDistrictCode((Integer) objs[1]); aamData.setBranchFulleName((String) objs[2]); } else if ("district".equalsIgnoreCase(typeOfData)) { aamData.setDistrict((String) objs[0]); aamData.setBuCode((Integer) objs[1]); } else if ("bu".equalsIgnoreCase(typeOfData)) { aamData.setBu((String) objs[1]); } } else { if ("office".equalsIgnoreCase(typeOfData)) { aamData.setOfficeCode("0"); } else if ("ssc".equalsIgnoreCase(typeOfData)) { aamData.setSscCode(0); } else if ("city".equalsIgnoreCase(typeOfData)) { aamData.setCityCode(0); } else if ("branch".equalsIgnoreCase(typeOfData)) { aamData.setBranchCode(0); } else if ("district".equalsIgnoreCase(typeOfData)) { aamData.setDistrictCode(0); } else if ("bu".equalsIgnoreCase(typeOfData)) { aamData.setBuCode(0); } } session.flush(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); LogsMaintenance logsMain = new LogsMaintenance(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); logsMain.insertLogs("AamDataMaintenance", Level.SEVERE + "", errors.toString()); } finally { try { HibernateFactory.close(session); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } } return aamData; }