Example usage for org.hibernate Query setCacheable

List of usage examples for org.hibernate Query setCacheable

Introduction

In this page you can find the example usage for org.hibernate Query setCacheable.

Prototype

Query<R> setCacheable(boolean cacheable);

Source Link

Document

Enable/disable second level query (result) caching for this query.

Usage

From source file:com.enonic.cms.store.dao.FindContentByKeysQuerier.java

License:Open Source License

List<ContentEntity> queryContent(final Collection<ContentKey> contentKeys) {
    final SelectBuilder hqlQuery = new SelectBuilder(0);
    hqlQuery.addSelect("c");
    hqlQuery.addFromTable(ContentEntity.class.getName(), "c", SelectBuilder.NO_JOIN, null);

    if (eagerFetchingIsSafe(contentKeys)) {
        if (contentEagerFetches.hasTable(ContentEagerFetches.Table.ACCESS)) {
            hqlQuery.addFromTable("c.contentAccessRights", null, SelectBuilder.LEFT_JOIN_FETCH, null);
        }//from  www  .  j a va  2  s . c o  m
        if (contentEagerFetches.hasTable(ContentEagerFetches.Table.MAIN_VERSION)) {
            hqlQuery.addFromTable("c.mainVersion", null, SelectBuilder.LEFT_JOIN_FETCH, null);
        }
        if (contentEagerFetches.hasTable(ContentEagerFetches.Table.SECTION_CONTENT)) {
            hqlQuery.addFromTable("c.sectionContents", null, SelectBuilder.LEFT_JOIN_FETCH, null);
        }
        if (contentEagerFetches.hasTable(ContentEagerFetches.Table.DIRECT_MENUITEM_PLACEMENT)) {
            hqlQuery.addFromTable("c.directMenuItemPlacements", null, SelectBuilder.LEFT_JOIN_FETCH, null);
        }
        if (contentEagerFetches.hasTable(ContentEagerFetches.Table.CONTENT_HOME)) {
            hqlQuery.addFromTable("c.contentHomes", null, SelectBuilder.LEFT_JOIN_FETCH, null);
        }
    }

    hqlQuery.addFilter("AND", new InClauseBuilder<ContentKey>("c.key", contentKeys) {
        public void appendValue(StringBuffer sql, ContentKey value) {
            sql.append(value.toString());
        }
    }.toString());

    final Query compiled = hibernateSession.createQuery(hqlQuery.toString());
    compiled.setReadOnly(fetchEntitiesAsReadOnly);
    compiled.setCacheable(false);
    //noinspection unchecked
    return compiled.list();
}

From source file:com.enonic.cms.store.dao.FindRelatedChildrenCommand.java

License:Open Source License

Collection<RelatedChildContent> execute(RelatedChildContentQuery relatedChildContentQuery) {
    if (relatedChildContentQuery.getContentVersions() == null
            || relatedChildContentQuery.getContentVersions().size() == 0) {
        throw new IllegalArgumentException("Given contentVersionKeys must contain values");
    }// w w w  .  j  av a2 s  . com

    String hql = getRelatedChildrenByKeyHQL(relatedChildContentQuery);

    Query compiled = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql);
    compiled.setCacheable(false);
    compiled.setReadOnly(true);
    compiled.setParameter("deleted", 0);

    if (!relatedChildContentQuery.isIncludeOfflineContent()) {
        compiled.setParameter("status", ContentStatus.APPROVED.getKey());
        compiled.setParameter("timeNow",
                relatedChildContentQuery.getNow().minuteOfHour().roundFloorCopy().toDate());
    }

    final List<ContentVersionKey> contentVersionKeys = relatedChildContentQuery.getContentVersions();
    for (int i = 0; i < contentVersionKeys.size(); i++) {
        compiled.setParameter("cv" + i, contentVersionKeys.get(i));
    }

    if (relatedChildContentQuery.hasSecurityFilter()) {
        compiled.setParameter("one", 1);
        List<GroupKey> securityFilter = Lists.newArrayList(relatedChildContentQuery.getSecurityFilter());
        for (int i = 0; i < securityFilter.size(); i++) {
            compiled.setParameter("g" + i, securityFilter.get(i));
        }
    }

    @SuppressWarnings({ "unchecked" })
    List<Object[]> list = compiled.list();

    final Set<ContentKey> contentKeys = new LinkedHashSet<ContentKey>(list.size());
    for (Object[] row : list) {
        contentKeys.add((ContentKey) row[1]);
    }

    final ContentMap contentMap = retrieveContent(contentKeys);

    final List<RelatedChildContent> relatedChildContrents = new ArrayList<RelatedChildContent>();
    for (Object[] row : list) {
        ContentVersionKey versionKey = (ContentVersionKey) row[0];
        ContentKey contentKey = (ContentKey) row[1];
        ContentEntity content = contentMap.get(contentKey);
        RelatedChildContent relatedChildContent = new RelatedChildContent(versionKey, content);
        relatedChildContrents.add(relatedChildContent);
    }

    return relatedChildContrents;
}

From source file:com.enonic.cms.store.dao.FindRelatedParentsCommand.java

License:Open Source License

Collection<RelatedParentContent> execute(final RelatedParentContentQuery relatedParentContentQuery) {
    if (relatedParentContentQuery.getContents() == null
            || relatedParentContentQuery.getContents().size() == 0) {
        throw new IllegalArgumentException("Given childContentKeys must contain values");
    }//from  w w w .  j a  v  a  2  s.c o m

    final String hql = getRelatedParentsByKeyHQL(relatedParentContentQuery);

    final Query compiled = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql);
    compiled.setCacheable(false);
    compiled.setReadOnly(true);
    compiled.setParameter("deleted", 0);

    if (!relatedParentContentQuery.isIncludeOfflineContent()) {
        compiled.setParameter("timeNow",
                relatedParentContentQuery.getNow().minuteOfHour().roundFloorCopy().toDate());
        compiled.setParameter("status", ContentStatus.APPROVED.getKey());
    }

    final List<ContentKey> childContentKeys = relatedParentContentQuery.getContents();
    for (int i = 0; i < childContentKeys.size(); i++) {
        compiled.setParameter("c" + i, childContentKeys.get(i));
    }

    if (relatedParentContentQuery.hasSecurityFilter()) {
        compiled.setParameter("one", 1);
        final List<GroupKey> securityFilter = Lists.newArrayList(relatedParentContentQuery.getSecurityFilter());
        for (int i = 0; i < securityFilter.size(); i++) {
            compiled.setParameter("g" + i, securityFilter.get(i));
        }
    }

    @SuppressWarnings({ "unchecked" })
    List<Object[]> list = compiled.list();

    final Set<ContentKey> contentKeys = new LinkedHashSet<ContentKey>(list.size());
    for (Object[] row : list) {
        contentKeys.add((ContentKey) row[2]);
    }

    final ContentMap contentMapByKey = retrieveContent(contentKeys);

    final List<RelatedParentContent> relatedChildContents = new ArrayList<RelatedParentContent>();
    for (Object[] row : list) {
        ContentKey childContentKey = (ContentKey) row[0];
        ContentVersionKey parentContentMainVersionKey = (ContentVersionKey) row[1];
        ContentKey parentContentKey = (ContentKey) row[2];
        ContentEntity parentContent = contentMapByKey.get(parentContentKey);
        RelatedParentContent relatedParentContent = new RelatedParentContent(childContentKey, parentContent,
                parentContentMainVersionKey);
        relatedChildContents.add(relatedParentContent);
    }

    return relatedChildContents;
}

From source file:com.enonic.cms.store.dao.GroupEntityDao.java

License:Open Source License

public List<GroupEntity> findBySpecification(GroupSpecification spec) {
    String hqlQuery = createHqlQuery(spec);

    Query compiled = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hqlQuery);
    compiled.setCacheable(true);
    if (spec.getKey() != null) {
        compiled.setString("key", spec.getKey().toString());
    }//  w  w w . j  a  va2 s  .co  m
    if (spec.getName() != null) {
        compiled.setString("name", spec.getName());
    }
    if (spec.getSyncValue() != null) {
        compiled.setString("syncValue", spec.getSyncValue());
    }
    if (spec.getUserStoreKey() != null) {
        compiled.setInteger("userStoreKey", spec.getUserStoreKey().toInt());
    }
    if (spec.getType() != null) {
        compiled.setInteger("type", spec.getType().toInteger());
    }
    return compiled.list();
}

From source file:com.enonic.cms.store.dao.LogEntryEntityDao.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
public List<LogEntryKey> findBySpecification(LogEntrySpecification specification, final String orderBy) {

    final String logEntryKeysHQL = getLogEntryKeysHQL(specification, orderBy);
    Query compiled = getHibernateTemplate().getSessionFactory().getCurrentSession()
            .createQuery(logEntryKeysHQL);

    if (specification.getDateFilter() != null) {
        compiled.setDate("dateFilter", specification.getDateFilter());
    }//from w ww.j ava 2  s . co m

    if (specification.isDateSpanSet()) {
        specification.setDateSpanParameters(compiled);
    }

    compiled.setCacheable(true);

    @SuppressWarnings({ "unchecked" })
    LogEntryResultTransformer transformer = new LogEntryResultTransformer(
            specification.isAllowDuplicateEntries());

    return transformer.transformList(compiled.list());

}

From source file:com.enonic.cms.store.dao.MenuItemEntityDao.java

License:Open Source License

public List<MenuItemEntity> findBySpecification(MenuItemSpecification spec) {
    String hql = buildHQL(spec);//  ww  w .  java2  s  . c o  m
    Query compiled = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql);
    compiled.setCacheable(true);

    return (List<MenuItemEntity>) compiled.list();
}

From source file:com.enonic.cms.store.dao.SiteEntityDao.java

License:Open Source License

public List<SiteEntity> findByPublishPossible(final int contentTypeKey, final UserEntity user) {
    return executeListResult(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {

            StringBuffer hql = new StringBuffer();
            SelectBuilder sites = new SelectBuilder(hql, 0);
            sites.addSelect("sit");
            sites.addFromTable(SiteEntity.class.getName(), "sit", SelectBuilder.NO_JOIN, null);

            SelectBuilder mei = new SelectBuilder(3);
            mei.addSelect("mei.key");
            mei.addFromTable(MenuItemEntity.class.getName(), "mei", SelectBuilder.NO_JOIN, null);
            mei.append("left outer join mei.page.template pat");
            mei.addFilter("AND", "mei.site.key = sit.key");
            mei.addFilter("AND", "( mei.menuItemType = 6 or pat.type = 6 )");
            mei.addFilter("AND", "( mei.section = 1 )");

            SelectBuilder sctf = new SelectBuilder(9);
            sctf.addSelect("sctf.key");
            sctf.addFromTable(SectionContentTypeFilterEntity.class.getName(), "sctf", SelectBuilder.NO_JOIN,
                    null);//  ww  w  .  j a va 2s  .  co m
            sctf.addFilter("AND", "sctf.contentType.key = :contentTypeKey");
            sctf.addFilter("AND", "sctf.section.key = mei.key");

            mei.addFilter("AND", "exists (" + sctf.toString() + ")");

            if (!user.isEnterpriseAdmin()) {
                Collection<String> groupKeys = resolveUsersAllGroupMemberships(user);

                if (groupKeys.isEmpty()) {
                    return new ArrayList<SiteEntity>();
                } else {
                    SelectBuilder mia = new SelectBuilder(6);
                    mia.addSelect("mia.key.menuItemKey");
                    mia.addFromTable(MenuItemAccessEntity.class.getName(), "mia", SelectBuilder.NO_JOIN, null);
                    mia.addFilter("AND", "mia.addAccess = 1");
                    mia.addFilter("AND", "mia.key.menuItemKey = mei.key");
                    mia.addFilter("AND", new InClauseBuilder<String>("mia.key.groupKey", groupKeys) {
                        public void appendValue(StringBuffer sql, String value) {
                            sql.append("'").append(value).append("'");
                        }
                    }.toString());
                    mei.addFilter("AND", "exists (" + mia.toString() + ")");
                }
            }

            sites.addFilter("AND", "exists (" + mei.toString() + ")");

            Query compiled = session.createQuery(hql.toString());
            compiled.setCacheable(false);
            compiled.setInteger("contentTypeKey", contentTypeKey);
            return compiled.list();
        }
    });
}

From source file:com.enonic.cms.store.dao.UserEntityDao.java

License:Open Source License

public List<UserEntity> findBySpecification(final UserSpecification spec) {

    String hqlQuery = createHqlQuery(spec);

    Query compiled = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hqlQuery);
    compiled.setCacheable(true);
    if (spec.getKey() != null) {
        compiled.setParameter("key", spec.getKey());
    }/*from www .  j av a 2s.co  m*/
    if (spec.getName() != null) {
        compiled.setString("name", spec.getName().toLowerCase());
    }
    if (spec.getSyncValue() != null) {
        compiled.setString("syncValue", spec.getSyncValue());
    }
    if (spec.getUserStoreKey() != null) {
        compiled.setInteger("userStoreKey", spec.getUserStoreKey().toInt());
    }
    if (spec.getType() != null) {
        compiled.setInteger("type", spec.getType().getKey());
    }
    if (spec.getUserGroupKey() != null) {
        compiled.setString("userGroupKey", spec.getUserGroupKey().toString());
    }
    if (spec.getEmail() != null) {
        compiled.setString("email", spec.getEmail().toLowerCase());
    }
    return compiled.list();
}

From source file:com.example.app.model.profile.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./*  www.  j a  va 2 s.com*/
 * @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 || 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.model.profile.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 v  a  2 s.c  o 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 || 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);
}