Java Code Examples for org.hibernate.query.Query#setParameterList()

The following examples show how to use org.hibernate.query.Query#setParameterList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KickstartFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fail the kickstart sessions associated with the given actions and servers.
 *
 * @param actionsToDelete Actions associated with the kickstart sessions to fail.
 * @param servers Servers assocaited with the kickstart sessions to fail.
 */
public static void failKickstartSessions(Set actionsToDelete, Set servers) {
    Session session = HibernateFactory.getSession();
    KickstartSessionState failed = KickstartFactory.SESSION_STATE_FAILED;
    Query kickstartSessionQuery = session.getNamedQuery(
            "KickstartSession.findPendingForActions");
    kickstartSessionQuery.setParameterList("actions_to_delete", actionsToDelete);
    int subStart = 0;
    List serverList = new ArrayList(servers);
    while (subStart < servers.size()) {
        int subLength = subStart + IN_CLAUSE_MAX_SIZE >= serverList.size() ?
                serverList.size() - subStart : IN_CLAUSE_MAX_SIZE;
        List subClause = serverList.subList(subStart, subStart + subLength);
        subStart += subLength;
        kickstartSessionQuery.setParameterList("servers", subClause);
        List ksSessions = kickstartSessionQuery.list();
        for (Object next : ksSessions) {
            KickstartSession ks = (KickstartSession)next;
            log.debug("Failing kickstart associated with action: " + ks.getId());
            ks.setState(failed);
            ks.setAction(null);

            setKickstartSessionHistoryMessage(ks, failed, KICKSTART_CANCELLED_MESSAGE);
        }
    }
}
 
Example 2
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> getOwnersByProjectIds(List<String> projectIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_IDS_HQL);
    query.setParameterList("ids", projectIds);

    @SuppressWarnings("unchecked")
    List<ProjectEntity> projectEntities = query.list();
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    Map<String, String> projectOwnersMap = new HashMap<>();
    for (ProjectEntity projectEntity : projectEntities) {
      projectOwnersMap.put(projectEntity.getId(), projectEntity.getOwner());
    }
    return projectOwnersMap;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getOwnersByProjectIds(projectIds);
    } else {
      throw ex;
    }
  }
}
 
Example 3
Source File: UserRatingHibernateDao.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Map<String, UserRatingModel> selectAllByTimeAndUserJids(Instant time, Set<String> userJids) {
    if (userJids.isEmpty()) {
        return ImmutableMap.of();
    }

    // selects the row for each `userJid` with the latest `time` before the given time

    Query<UserRatingModel> query = currentSession().createQuery(
            "SELECT t1 FROM jophiel_user_rating t1 "
                    + "LEFT OUTER JOIN jophiel_user_rating t2 "
                    + "ON (t1.userJid = t2.userJid AND t1.time < t2.time AND t2.time < :time) "
                    + "WHERE t1.time < :time AND t1.userJid IN :userJids AND t2.userJid IS NULL",
            UserRatingModel.class);

    query.setParameter("time", time);
    query.setParameterList("userJids", userJids);

    return query.getResultList()
            .stream()
            .collect(Collectors.toMap(m -> m.userJid, m -> m));
}
 
Example 4
Source File: ExperimentDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> getProjectIdsByExperimentIds(List<String> experimentIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query experimentQuery = session.createQuery(PROJ_IDS_BY_EXP_IDS_HQL);
    experimentQuery.setParameterList("experimentIds", experimentIds);
    experimentQuery.setParameter("deleted", false);
    List<ExperimentEntity> experimentEntities = experimentQuery.list();

    Map<String, String> projectIdFromExperimentMap = new HashMap<>();
    for (ExperimentEntity experimentEntity : experimentEntities) {
      projectIdFromExperimentMap.put(experimentEntity.getId(), experimentEntity.getProject_id());
    }
    return projectIdFromExperimentMap;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getProjectIdsByExperimentIds(experimentIds);
    } else {
      throw ex;
    }
  }
}
 
Example 5
Source File: OutcomeDAO.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
   @SuppressWarnings("unchecked")
   public List<Outcome> getOutcomesSortedByName(String search, Set<Integer> organisationIds) {
String queryString = FIND_OUTCOMES_SORTED_BY_NAME;
if (StringUtils.isNotBlank(search)) {
    queryString = queryString.replace("?", "(o.name LIKE :search OR o.code LIKE :search) AND ?");
}
queryString = queryString.replace("?", "(o.organisation IS NULL ?)");
if (organisationIds != null && !organisationIds.isEmpty()) {
    queryString = queryString.replace("?", "OR o.organisation.organisationId IN (:organisationIds)");
}
queryString = queryString.replace("?", "");

Query<Outcome> query = getSession().createQuery(queryString);
if (organisationIds != null && !organisationIds.isEmpty()) {
    query.setParameterList("organisationIds", organisationIds);
}
if (StringUtils.isNotBlank(search)) {
    query.setParameter("search", "%" + search + "%");
}

return query.list();
   }
 
Example 6
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Long getExperimentRunCount(List<String> projectIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query<?> query = session.createQuery(GET_PROJECT_EXPERIMENT_RUNS_COUNT_HQL);
    query.setParameterList(ModelDBConstants.PROJECT_IDS, projectIds);
    Long count = (Long) query.uniqueResult();
    LOGGER.debug("ExperimentRun Count : {}", count);
    return count;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRunCount(projectIds);
    } else {
      throw ex;
    }
  }
}
 
Example 7
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getExperimentRunIdsByProjectIds(List<String> projectIds)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query experimentRunQuery = session.createQuery(GET_EXPERIMENT_RUN_BY_PROJECT_ID_HQL);
    experimentRunQuery.setParameterList("projectIds", projectIds);
    List<ExperimentRunEntity> experimentRunEntities = experimentRunQuery.list();

    List<String> experimentRunIds = new ArrayList<>();
    for (ExperimentRunEntity experimentRunEntity : experimentRunEntities) {
      experimentRunIds.add(experimentRunEntity.getId());
    }
    return experimentRunIds;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRunIdsByProjectIds(projectIds);
    } else {
      throw ex;
    }
  }
}
 
Example 8
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Long getExperimentCount(List<String> projectIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query<?> query = session.createQuery(GET_PROJECT_EXPERIMENTS_COUNT_HQL);
    query.setParameterList(ModelDBConstants.PROJECT_IDS, projectIds);
    Long count = (Long) query.uniqueResult();
    LOGGER.debug("Experiment Count : {}", count);
    return count;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentCount(projectIds);
    } else {
      throw ex;
    }
  }
}
 
Example 9
Source File: DatasetVersionDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean deleteDatasetVersionsByDatasetIDs(List<String> datasetIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    Query query = session.createQuery(DELETED_STATUS_DATASET_VERSION_BY_DATASET_QUERY_STRING);
    query.setParameter("deleted", true);
    query.setParameterList("datasetIds", datasetIds);
    int updatedCount = query.executeUpdate();
    transaction.commit();
    LOGGER.debug("DatasetVersion deleted successfully, updated Row: {}", updatedCount);
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteDatasetVersionsByDatasetIDs(datasetIds);
    } else {
      throw ex;
    }
  }
}
 
Example 10
Source File: HibernateTrackedEntityProgramOwnerStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<TrackedEntityProgramOwner> getTrackedEntityProgramOwners( List<Long> teiIds, long programId )
{
    String hql = "from TrackedEntityProgramOwner tepo where tepo.entityInstance.id in (:teiIds) and tepo.program.id=(:programId) ";
    Query<TrackedEntityProgramOwner> q = getQuery( hql );
    q.setParameterList( "teiIds", teiIds );
    q.setParameter( "programId", programId );
    return q.list();
}
 
Example 11
Source File: HibernatePotentialDuplicateStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<PotentialDuplicate> getAllByQuery( PotentialDuplicateQuery query )
{
    if ( query.getTeis() != null && query.getTeis().size() > 0 )
    {
        Query<PotentialDuplicate> hibernateQuery = getTypedQuery(
            "from PotentialDuplicate pr where pr.teiA in (:uids)  or pr.teiB in (:uids)" );
        hibernateQuery.setParameterList( "uids", query.getTeis() );
        return hibernateQuery.getResultList();
    }
    else
    {
        return getAll();
    }
}
 
Example 12
Source File: HibernatePotentialDuplicateStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int getCountByQuery( PotentialDuplicateQuery query )
{
    if ( query.getTeis() != null && query.getTeis().size() > 0 )
    {
        Query<Long> hibernateQuery = getTypedQuery(
            "select count(*) from PotentialDuplicate pr where pr.teiA in (:uids)  or pr.teiB in (:uids)" );
        hibernateQuery.setParameterList( "uids", query.getTeis() );
        return hibernateQuery.getSingleResult().intValue();
    }
    else
    {
        return getCount();
    }
}
 
Example 13
Source File: PaymentModuleGenericDAOImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
private void setQueryParameters(final Query query, final Object[] parameters) {
    if (parameters != null) {
        int idx = 1;
        for (Object param : parameters) {
            if (param instanceof Collection) {
                query.setParameterList(String.valueOf(idx), (Collection) param);
            } else {
                query.setParameter(String.valueOf(idx), param);
            }
            idx++;
        }
    }
}
 
Example 14
Source File: HibernateTrackedEntityProgramOwnerStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<TrackedEntityProgramOwner> getTrackedEntityProgramOwners( List<Long> teiIds )
{
    String hql = "from TrackedEntityProgramOwner tepo where tepo.entityInstance.id in (:teiIds)";
    Query<TrackedEntityProgramOwner> q = getQuery( hql );
    q.setParameterList( "teiIds", teiIds );
    return q.list();
}
 
Example 15
Source File: HibernateOrmImpl.java    From tephra with MIT License 5 votes vote down vote up
private Query createQuery(String dataSource, Mode mode, StringBuilder hql, Object[] args, boolean lock, int size, int page) {
    if (logger.isDebugEnable())
        logger.debug("hql:{};args:{}", hql, converter.toString(args));

    Query query = session.get(dataSource, mode).createQuery(replaceArgs(hql));
    if (lock) {
        session.beginTransaction();
        query.setLockOptions(LockOptions.UPGRADE);
    }
    if (size > 0)
        query.setFirstResult(size * (page - 1)).setMaxResults(size);

    if (validator.isEmpty(args))
        return query;

    for (int i = 0; i < args.length; i++) {
        if (args[i] == null)
            query.setParameter(ARG[2] + i, args[i]);
        else if (args[i] instanceof Collection<?>)
            query.setParameterList(ARG[2] + i, (Collection<?>) args[i]);
        else if (args[i].getClass().isArray())
            query.setParameterList(ARG[2] + i, (Object[]) args[i]);
        else
            query.setParameter(ARG[2] + i, args[i]);
    }

    return query;
}
 
Example 16
Source File: GenericDAOHibernateImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
private void setQueryParameters(final Query query, final Object[] parameters) {
    if (parameters != null) {
        int idx = 1;
        for (Object param : parameters) {
            if (param instanceof Collection) {
                query.setParameterList(String.valueOf(idx), (Collection) param);
            } else {
                query.setParameter(String.valueOf(idx), param);
            }
            idx++;
        }
    }
}
 
Example 17
Source File: ActionFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Delete the server actions associated with the given set of parent actions.
 * @param parentActions Set of parent actions.
 */
public static void deleteServerActionsByParent(Set parentActions) {
    Session session = HibernateFactory.getSession();

    Query serverActionsToDelete =
            session.getNamedQuery("ServerAction.deleteByParentActions");
    serverActionsToDelete.setParameterList("actions", parentActions);
    serverActionsToDelete.executeUpdate();
}
 
Example 18
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private List<ProjectEntity> getProjectEntityByBatchIds(Session session, List<String> projectIds) {
  Query query = session.createQuery(GET_PROJECT_BY_IDS_HQL);
  query.setParameterList("ids", projectIds);
  return query.list();
}
 
Example 19
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
/**
 * returns a list of projectIds accessible to the user passed as an argument within the workspace
 * passed as an argument. For no auth returns the list of non deleted projects
 */
@Override
public List<String> getWorkspaceProjectIDs(String workspaceName, UserInfo currentLoginUserInfo)
    throws InvalidProtocolBufferException {
  if (!roleService.IsImplemented()) {
    try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
      return session.createQuery(NON_DELETED_PROJECT_IDS).list();
    }
  } else {

    // get list of accessible projects
    @SuppressWarnings("unchecked")
    List<String> accessibleProjectIds =
        roleService.getAccessibleResourceIds(
            null,
            new CollaboratorUser(authService, currentLoginUserInfo),
            ProjectVisibility.PRIVATE,
            ModelDBServiceResourceTypes.PROJECT,
            Collections.EMPTY_LIST);
    LOGGER.debug(
        "accessible Project Ids in function getWorkspaceProjectIDs : {}", accessibleProjectIds);

    // resolve workspace
    WorkspaceDTO workspaceDTO =
        roleService.getWorkspaceDTOByWorkspaceName(currentLoginUserInfo, workspaceName);

    List<String> resultProjects = new LinkedList<String>();
    try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
      @SuppressWarnings("unchecked")
      Query<String> query = session.createQuery(IDS_FILTERED_BY_WORKSPACE);
      query.setParameterList(ModelDBConstants.PROJECT_IDS, accessibleProjectIds);
      query.setParameter(ModelDBConstants.WORKSPACE, workspaceDTO.getWorkspaceId());
      query.setParameter(
          ModelDBConstants.WORKSPACE_TYPE, workspaceDTO.getWorkspaceType().getNumber());
      resultProjects = query.list();

      // in personal workspace show projects directly shared
      if (workspaceDTO
          .getWorkspaceName()
          .equals(authService.getUsernameFromUserInfo(currentLoginUserInfo))) {
        LOGGER.debug("Workspace and current login user match");
        List<String> directlySharedProjects =
            roleService.getSelfDirectlyAllowedResources(
                ModelDBServiceResourceTypes.PROJECT, ModelDBServiceActions.READ);
        query = session.createQuery(NON_DELETED_PROJECT_IDS_BY_IDS);
        query.setParameterList(ModelDBConstants.PROJECT_IDS, directlySharedProjects);
        resultProjects.addAll(query.list());
        LOGGER.debug(
            "accessible directlySharedProjects Ids in function getWorkspaceProjectIDs : {}",
            directlySharedProjects);
      }
    }
    LOGGER.debug(
        "Total accessible project Ids in function getWorkspaceProjectIDs : {}", resultProjects);
    return resultProjects;
  }
}
 
Example 20
Source File: DatasetDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private List<DatasetEntity> getDatasetEntityList(Session session, List<String> datasetIds) {
  Query query = session.createQuery(GET_DATASET_BY_IDS_QUERY);
  query.setParameterList("ids", datasetIds);
  return query.list();
}