List of usage examples for org.hibernate Query setCacheable
Query<R> setCacheable(boolean cacheable);
From source file:com.example.app.model.resource.ResourceDAO.java
License:Open Source License
/** * Get all the resources of a specific type. * * @param <T> The type of resource * @param resultType The type of resource * * @return the resources, sorted by create date *///w w w .j ava 2 s . c om @SuppressWarnings("unchecked") public <T extends Resource> List<T> getResources(@NotNull Class<T> resultType) { @SuppressWarnings("StringBufferReplaceableByString") StringBuilder hql = new StringBuilder("from "); hql.append(resultType.getSimpleName()); hql.append(" as r order by r.createTime"); final Query q = getSession().createQuery(hql.toString()); // Not an expensive query and not called frequently q.setCacheable(false); return q.list(); }
From source file:com.example.app.model.user.UserDAO.java
License:Open Source License
/** * Get a User for the given Principal.// ww w . j av a2 s.com * * @param principal the Principal to search for * @param status optional status to limit. * * @return a User, or null if none exists for the given Principal */ @Nullable public User getUserForPrincipal(@Nullable Principal principal, @Nullable PrincipalStatus... status) { if (principal == null) return null; String queryString = "SELECT u FROM User u INNER JOIN u.principal p WHERE p = :principal"; final boolean hasStatus = status != null && status.length > 0; if (hasStatus) queryString += " AND p.status IN (:status)"; final Query query = getSession().createQuery(queryString); query.setCacheable(true); query.setCacheRegion(ProjectCacheRegions.MEMBER_QUERY); query.setParameter("principal", principal); if (hasStatus) query.setParameterList("status", status); return (User) query.uniqueResult(); }
From source file:com.example.app.model.user.UserDAO.java
License:Open Source License
/** * Get users matching the specified parameters. * All parameters are optional. If none are specified, an empty list is returned. * * @param firstName first name./*from w w w . j av a 2 s. c om*/ * @param lastName last name. * @param email email address. * @param exclude optional exclusion collection. * * @return the user list. */ public List<User> getUsers(@Nullable String firstName, @Nullable String lastName, @Nullable String email, @Nullable Collection<User> exclude) { boolean hasFirst = !isEmptyString(firstName); boolean hasLast = !isEmptyString(lastName); boolean hasEmail = !isEmptyString(email); boolean hasExclude = exclude != null && !exclude.isEmpty(); if (!hasFirst && !hasLast && !hasEmail) return new ArrayList<>(); StringBuilder hql = new StringBuilder(); hql.append("SELECT DISTINCT user FROM User user \n" + " INNER JOIN user.principal as p\n" + " LEFT JOIN p.contact as c \n"); if (hasFirst || hasLast) { hql.append(" LEFT JOIN c.name as n\n"); } if (hasEmail) { hql.append(" LEFT JOIN c.emailAddresses as ea\n"); } hql.append(" WHERE ("); if (hasFirst) { hql.append(" LOWER(n.first) LIKE :firstName"); } if (hasLast) { if (hasFirst) hql.append(" OR"); hql.append(" LOWER(n.last) LIKE :lastName"); } if (hasEmail) { if (hasFirst || hasLast) hql.append(" OR"); hql.append(" LOWER(ea.email) LIKE :email"); } hql.append(')'); if (hasExclude) { hql.append(" AND user NOT IN (:exclude)"); } final Session session = getSession(); final Query query = session.createQuery(hql.toString()); query.setCacheable(true); query.setCacheRegion(ProjectCacheRegions.MEMBER_QUERY); if (hasFirst) query.setParameter("firstName", '%' + firstName.trim().toLowerCase() + '%'); if (hasLast) query.setParameter("lastName", '%' + lastName.trim().toLowerCase() + '%'); if (hasEmail) query.setParameter("email", '%' + email.trim().toLowerCase() + '%'); if (hasExclude) query.setParameterList("exclude", exclude); @SuppressWarnings("unchecked") final List<User> list = query.list(); return list; }
From source file:com.example.app.profile.model.company.CompanyDAO.java
License:Open Source License
/** * Get users matching the specified parameters. * All parameters are optional. If none are specified, an empty list is returned. * * @param firstName first name./* w w w.j a v a2 s. c om*/ * @param lastName last name. * @param email email address. * @param exclude optional exclusion collection. * @param company the company * * @return the user list. */ public List<User> getUsers(@Nullable String firstName, @Nullable String lastName, @Nullable String email, @Nullable Collection<User> exclude, @Nonnull Company company) { boolean hasFirst = !isEmptyString(firstName); boolean hasLast = !isEmptyString(lastName); boolean hasEmail = !isEmptyString(email); boolean hasExclude = exclude != null && !exclude.isEmpty(); if (!hasFirst && !hasLast && !hasEmail) return new ArrayList<>(); StringBuilder hql = new StringBuilder(); hql.append("SELECT DISTINCT user FROM Company ce\n" + " INNER JOIN ce.users user\n" + " INNER JOIN user.principal as p\n" + " LEFT JOIN p.contact as c \n"); if (hasFirst || hasLast) { hql.append(" LEFT JOIN c.name as n\n"); } if (hasEmail) { hql.append(" LEFT JOIN c.emailAddresses as ea\n"); } hql.append(" WHERE ("); if (hasFirst) { hql.append(" LOWER(n.first) LIKE :firstName"); } if (hasLast) { if (hasFirst) hql.append(" OR"); hql.append(" LOWER(n.last) LIKE :lastName"); } if (hasEmail) { if (hasFirst || hasLast) hql.append(" OR"); hql.append(" LOWER(ea.email) LIKE :email"); } hql.append(")\n"); if (hasExclude) { hql.append(" AND user NOT IN (:exclude)\n"); } hql.append("AND ce.id = :ceid"); final Session session = getSession(); final Query query = session.createQuery(hql.toString()); query.setCacheable(true); query.setCacheRegion(ProjectCacheRegions.MEMBER_QUERY); if (hasFirst) query.setParameter("firstName", '%' + firstName.trim().toLowerCase() + '%'); if (hasLast) query.setParameter("lastName", '%' + lastName.trim().toLowerCase() + '%'); if (hasEmail) query.setParameter("email", '%' + email.trim().toLowerCase() + '%'); if (hasExclude) query.setParameterList("exclude", exclude); query.setParameter("ceid", company.getId()); @SuppressWarnings("unchecked") final List<User> list = query.list(); return list; }
From source file:com.example.app.profile.model.ProfileDAO.java
License:Open Source License
/** * Test if the specified user can perform all the operations on any of the specified profiles. * * @param user the User./* w w w. j a v a 2s. c o m*/ * @param profiles the Profiles. * @param timeZone the timezone. * @param operations the MembershipOperations to check * * @return true or false. */ @Contract("null,_,_->false") public boolean canOperate(@Nullable User user, @Nonnull Collection<Profile> profiles, TimeZone timeZone, @Nonnull MembershipOperation... operations) { if (user != null && _appUtil.userHasAdminRole(user)) return true; if (user == null || profiles.isEmpty()) return false; final Date now = convertForPersistence(getZonedDateTimeForComparison(timeZone)); Preconditions.checkArgument(operations.length > 0); final Query query = getSession().createQuery("SELECT COUNT(m) FROM Membership m INNER JOIN m.profile p\n" + " INNER JOIN m.operations op\n" + " WHERE m.user = :user\n" + " AND p IN (:profiles)\n" + " AND op IN (:operations)\n" + " AND (m.startDate IS NULL OR m.startDate <= :today)\n" + " AND (m.endDate IS NULL OR m.endDate >= :today)\n" + " GROUP BY m\n" + " HAVING COUNT(op) = :operationCount"); query.setCacheable(true).setCacheRegion(ProjectCacheRegions.PROFILE_QUERY); query.setParameter("user", user); query.setParameterList("profiles", profiles); query.setParameterList("operations", operations); query.setParameter("today", now); query.setInteger("operationCount", operations.length); return Optional.ofNullable(((Number) query.uniqueResult())).map(Number::intValue).map(i -> i > 0) .orElse(false); }
From source file:com.example.app.profile.model.ProfileDAO.java
License:Open Source License
/** * Returns a boolean flag on whether or not the given User can perform the given MembershipOperation on the given Profile * * @param user the User, may be null// w w w . j a va 2 s .co m * @param profileType the ProfileType. * @param operations the MembershipOperations to check * @param timeZone the timezone. * * @return a boolean flag. If true, the given user can perform the given operation on the given profile */ public boolean canOperate(@Nullable User user, @Nullable ProfileType profileType, TimeZone timeZone, MembershipOperation... operations) { if (user != null && _appUtil.userHasAdminRole(user)) return true; if (user == null || profileType == null) return false; Preconditions.checkArgument(operations.length > 0); final Date now = convertForPersistence(getZonedDateTimeForComparison(timeZone)); final Query query = getSession().createQuery( "SELECT COUNT(m) FROM Membership m INNER JOIN m.profile p INNER JOIN p.profileType pt\n" + " INNER JOIN m.operations op\n" + " WHERE m.user = :user\n" + " AND pt.id = :profileTypeId\n" + " AND op IN (:operations)\n" + " AND (m.startDate IS NULL OR m.startDate <= :today)\n" + " AND (m.endDate IS NULL OR m.endDate >= :today)\n" + " GROUP BY m\n" + " HAVING COUNT(op) = :operationCount"); query.setCacheable(true).setCacheRegion(ProjectCacheRegions.PROFILE_QUERY); query.setParameter("user", user); query.setParameter("profileTypeId", profileType.getId()); query.setParameterList("operations", operations); query.setParameter("today", now); query.setInteger("operationCount", operations.length); return Optional.ofNullable(((Number) query.uniqueResult())).map(Number::intValue).map(i -> i > 0) .orElse(false); }
From source file:com.gemstone.gemfire.modules.HibernateJUnitTest.java
License:Apache License
@Ignore @Test/* w ww . j a v a2 s . com*/ public void testQueryCache() throws Exception { Session session = getSessionFactory(null).openSession(); Query q = session.createQuery("from Event"); q.setCacheable(true); List l = q.list(); log.info("list:" + l); // log.info("Sleeping for 10 seconds"); // Thread.sleep(10000); l = q.list(); log.info("list2:" + l); log.info("updating an event"); session.beginTransaction(); Event e = (Event) l.get(0); e.setDate(new Date()); session.saveOrUpdate(e); session.getTransaction().commit(); l = q.list(); log.info("list3:" + l); }
From source file:com.gisgraphy.domain.repository.AdmDao.java
License:Open Source License
@Override public Adm get(final Long id) { Assert.notNull(id, "Can not retrieve an Ogject with a null id"); Adm returnValue = null;/* w w w . j ava2s .c o m*/ try { return (Adm) this.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { String queryString = "from " + persistentClass.getSimpleName() + " o where o.id=" + id; Query qry = session.createQuery(queryString); qry.setCacheable(true); return (Adm) qry.uniqueResult(); } }); } catch (Exception e) { logger.info("could not retrieve object of type " + persistentClass.getSimpleName() + " with id " + id, e); } return returnValue; }
From source file:com.gisgraphy.domain.repository.AdmDao.java
License:Open Source License
public Adm getAdm1(final String countryCode, final String adm1Code) { Assert.notNull(countryCode);//from w w w. j av a 2s . c om Assert.notNull(adm1Code); return (Adm) this.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { String queryString = "from " + Adm.class.getSimpleName() + " as a where a.countryCode = ? and a.adm1Code= ? and a.level=1"; Query qry = session.createQuery(queryString); qry.setCacheable(true); qry.setParameter(0, countryCode.toUpperCase()); qry.setParameter(1, adm1Code); Adm result = (Adm) qry.uniqueResult(); return result; } }); }
From source file:com.gisgraphy.domain.repository.AdmDao.java
License:Open Source License
public Adm getAdm2(final String countryCode, final String adm1Code, final String adm2Code) { Assert.notNull(countryCode);//from ww w.ja v a2 s. co m Assert.notNull(adm1Code); Assert.notNull(adm2Code); return (Adm) this.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { String queryString = "from " + Adm.class.getSimpleName() + " as a where a.countryCode=? and a.adm2Code=?"; if (!"00".equals(adm1Code)) { queryString += "and a.adm1Code= ?"; } queryString += " and a.level=2"; Query qry = session.createQuery(queryString); qry.setCacheable(true); qry.setParameter(0, countryCode.toUpperCase()); qry.setParameter(1, adm2Code); if (!"00".equals(adm1Code)) { qry.setParameter(2, adm1Code); } Adm result; try { result = (Adm) qry.uniqueResult(); } catch (HibernateException e) { if (!"00".equals(adm1Code)) { throw e; } else { logger.error("Can not retrieve Adm for countrycode=" + countryCode + " and adm2code=" + adm2Code + " in flex mode : result is ambiguous"); return null; } } return result; } }); }