Example usage for org.hibernate Query setParameterList

List of usage examples for org.hibernate Query setParameterList

Introduction

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

Prototype

Query<R> setParameterList(int position, Object[] values);

Source Link

Usage

From source file:com.example.app.model.repository.RepositoryDAO.java

License:Open Source License

/**
 * Get a list of RepositoryItemRelations that the given User has access to, filtered by the given RepositoryItem subclass
 *
 * @param <RI> the RepositoryItem subclass
 * @param user the User to search for//from w ww.j a  v  a 2 s.  c  o  m
 * @param repos the repositories to retrieve the items from
 * @param clazz the RepositoryItem subclass to filter by
 * @param statuses optional statuses.
 *
 * @return a list of all RepositoryItemRelations for the given user, subclass combination
 */
public <RI extends RepositoryItem> List<RI> getRepositoryItemsForUser(@Nonnull User user,
        @Nonnull List<Repository> repos, @Nonnull Class<RI> clazz, @Nullable RepositoryItemStatus... statuses) {
    boolean hasStatuses = statuses != null && statuses.length > 0;
    String hql = "SELECT DISTINCT ri\n" + "FROM Membership m,\n" + ' ' + clazz.getName() + " ri,\n"
            + "RepositoryItemRelation repoItemRelation\n" + "INNER JOIN m.profile owner\n"
            + "INNER JOIN owner.repository repo\n" + "WHERE m.user = :user \n" + "AND repo.id IN (:repoIds) \n"
            + "AND repo.id = repoItemRelation.repository.id\n"
            + "AND ri.id = repoItemRelation.repositoryItem.id\n"
            + (hasStatuses ? "AND ri.status IN (:statuses)" : "") + "ORDER BY ri.createTime ASC \n";
    Query query = getSession().createQuery(hql).setParameter("user", user)
            .setParameterList("repoIds", repos.stream().map(Repository::getId).collect(Collectors.toList()))
            .setCacheable(true).setCacheRegion(ProjectCacheRegions.ENTITY_QUERY);
    if (hasStatuses)
        query.setParameterList("statuses", statuses);
    @SuppressWarnings("unchecked")
    List<RI> list = query.list();
    return list;
}

From source file:com.example.app.model.user.UserDAO.java

License:Open Source License

/**
 * Get a User for the given Principal.//from  ww w .  ja va 2 s . co m
 *
 * @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.//w  ww. j ava  2s  .c o  m
 * @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./* ww  w.jav a  2 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 ww . j  av a2s  .co 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/*from  www.  j a  v a2  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 && _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.example.app.profile.model.user.UserDAO.java

License:Open Source License

/**
 * Gets users by email address./*ww w .  ja v  a 2s  .c  o m*/
 *
 * @param emailAddress the email address
 * @param domainList authentication domain list.
 * @return the users by email address.
 */
@SuppressWarnings("unchecked")
public List<User> getUsersByEmailAddress(String emailAddress, AuthenticationDomainList domainList) {
    return (List<User>) doInTransaction(session -> {
        @Language("HQL")
        String hql = "SELECT DISTINCT u FROM User u INNER JOIN u.principal p\n"
                + "INNER JOIN p.credentials cred\n" + "INNER JOIN p.authenticationDomains ad\n"
                + "INNER JOIN p.contact c INNER JOIN c.emailAddresses ea\n"
                + "WHERE (LOWER(ea.email) = LOWER(:email) OR LOWER(cred.username) = LOWER(:email))\n";
        if (!domainList.isEmpty()) {
            hql += " AND ad IN (:authDomains)";
        }

        Query query = session.createQuery(hql).setParameter("email", emailAddress);
        if (!domainList.isEmpty()) {
            query.setParameterList("authDomains", domainList.getAuthenticationDomainList());
        }

        return query.list();
    });
}

From source file:com.fiveamsolutions.nci.commons.audit.AuditLogRecordSearchCriteria.java

License:Open Source License

private Query helpBuildQuery(Session session, StringBuffer query, String orderByProperty) {
    if (id != null) {
        query.append(String.format(" %s.entityId = :entityId OR ", ROOT_ALIAS));
        query.append(String.format("  (ald in elements(%s.details) ", ROOT_ALIAS));
        query.append("    AND (ald.oldValue = :entityIdStr OR ald.newValue = :entityIdStr)) ");
    } else {//  w  w  w.  j  av  a  2s . co m
        query.append(String.format(" %s.transactionId in (:transactionIds) ", ROOT_ALIAS));
    }

    query.append(orderByProperty);
    Query q = session.createQuery(query.toString());

    if (id != null) {
        q.setLong("entityId", getId());
        q.setString("entityIdStr", Long.toString(getId()));
    } else {
        q.setParameterList("transactionIds", getTransactionId());
    }

    return q;
}

From source file:com.fiveamsolutions.nci.commons.search.SearchableUtils.java

License:Open Source License

private static void setQueryParams(final Map<String, Object> params, Query q) {
    for (String key : params.keySet()) {
        Object value = params.get(key);
        if (value instanceof Collection<?>) {
            q.setParameterList(key, (Collection<?>) value);
        } else {//w w w .  j  a va  2  s  .co m
            q.setParameter(key, value);
        }
    }
}

From source file:com.fiveamsolutions.nci.commons.util.HibernateHelper.java

License:Open Source License

/**
 * Bind the parameters returned by {@link #buildInClause(List, String, Map)} to a hibernate Query.
 * @param query hibernate query to bind to
 * @param blocks blocks to be bound to query
 *///ww w.  java 2 s  .c  om
public static void bindInClauseParameters(Query query, Map<String, List<? extends Serializable>> blocks) {
    for (Map.Entry<String, List<? extends Serializable>> block : blocks.entrySet()) {
        query.setParameterList(block.getKey(), block.getValue());
    }
}