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

The following examples show how to use org.hibernate.query.Query#uniqueResult() . 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: 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 2
Source File: CredentialDAO.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Checks whether a user can login to the repository. The Credential must include the password.
    */
   @Override
   public boolean checkCredential(ICredentials credential) throws RepositoryRuntimeException {
if (log.isDebugEnabled()) {
    log.debug("Checking credential " + credential);
}

if (credential == null) {
    return false;
}

Session hibernateSession = getSessionFactory().getCurrentSession();
Query<?> query = hibernateSession.createQuery(CredentialDAO.CHECK_CREDENTIAL);
query.setParameter("name", credential.getName());
query.setParameter("password", String.valueOf(credential.getPassword()));

Long count = (Long) query.uniqueResult();
if (count > 2) {
    log.warn("More than one credential found for name " + credential.getName());
}
return count > 0;
   }
 
Example 3
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Project getProjectByID(String id) throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_ID_HQL);
    query.setParameter("id", id);
    ProjectEntity projectEntity = (ProjectEntity) query.uniqueResult();
    if (projectEntity == null) {
      String errorMessage = ModelDBMessages.PROJECT_NOT_FOUND_FOR_ID;
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getProjectByID(id);
    } else {
      throw ex;
    }
  }
}
 
Example 4
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Project setProjectVisibility(String projectId, ProjectVisibility projectVisibility)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_ID_HQL);
    query.setParameter("id", projectId);
    ProjectEntity projectEntity = (ProjectEntity) query.uniqueResult();

    Integer oldVisibilityInt = projectEntity.getProject_visibility();
    ProjectVisibility oldVisibility = ProjectVisibility.PRIVATE;
    if (oldVisibilityInt != null) {
      oldVisibility = ProjectVisibility.forNumber(oldVisibilityInt);
    }
    if (!oldVisibility.equals(projectVisibility)) {
      projectEntity.setProject_visibility(projectVisibility.ordinal());
      projectEntity.setDate_updated(Calendar.getInstance().getTimeInMillis());
      Transaction transaction = session.beginTransaction();
      session.update(projectEntity);
      transaction.commit();
      deleteOldVisibilityBasedBinding(
          oldVisibility,
          projectId,
          projectEntity.getWorkspace_type(),
          projectEntity.getWorkspace());
      createNewVisibilityBasedBinding(
          projectVisibility,
          projectId,
          projectEntity.getWorkspace_type(),
          projectEntity.getWorkspace());
    }
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return setProjectVisibility(projectId, projectVisibility);
    } else {
      throw ex;
    }
  }
}
 
Example 5
Source File: RepositoryDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public SetTagRequest.Response setTag(SetTagRequest request) throws ModelDBException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    RepositoryEntity repository = getRepositoryById(session, request.getRepositoryId(), true);

    boolean exists =
        VersioningUtils.commitRepositoryMappingExists(
            session, request.getCommitSha(), repository.getId());
    if (!exists) {
      throw new ModelDBException(
          "Commit_hash and repository_id mapping not found for repository "
              + repository.getId()
              + " commit "
              + " request.getCommitSha()",
          Code.NOT_FOUND);
    }

    Query query = session.createQuery(GET_TAG_HQL);
    query.setParameter("repositoryId", repository.getId());
    query.setParameter("tag", request.getTag());
    TagsEntity tagsEntity = (TagsEntity) query.uniqueResult();
    if (tagsEntity != null) {
      throw new ModelDBException("Tag '" + request.getTag() + "' already exists", Code.NOT_FOUND);
    }

    tagsEntity = new TagsEntity(repository.getId(), request.getCommitSha(), request.getTag());
    session.beginTransaction();
    session.save(tagsEntity);
    session.getTransaction().commit();
    return SetTagRequest.Response.newBuilder().build();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return setTag(request);
    } else {
      throw ex;
    }
  }
}
 
Example 6
Source File: McUsrAttemptDAO.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public boolean isMcContentAttempted(Long mcContentUid) {
final String IS_USER_ATTEMPT_EXIST_BY_MC_CONTENT = "select COUNT(*) > 0 FROM " + McUsrAttempt.class.getName()
	+ " AS attempt WHERE attempt.mcQueContent.mcContent.uid=:mcContentUid";

Query<Boolean> q = getSession().createQuery(IS_USER_ATTEMPT_EXIST_BY_MC_CONTENT, Boolean.class);
q.setParameter("mcContentUid", mcContentUid);
return q.uniqueResult();
   }
 
Example 7
Source File: AssessmentResultDAOHibernate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public Boolean isLastAttemptFinishedByUser(AssessmentUser user) {
Assessment assessment = user.getAssessment() == null ? user.getSession().getAssessment() : user.getAssessment();
Query<Boolean> q = getSession().createQuery(FIND_WHETHER_LAST_RESULT_FINISHED, Boolean.class);
q.setParameter("userId", user.getUserId());
q.setParameter("assessmentUid", assessment.getUid());
return q.uniqueResult();
   }
 
Example 8
Source File: HibernateUserCredentialsStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public UserCredentials getUserCredentialsByOpenId( String openId )
{
    Query<UserCredentials> query = getQuery( "from UserCredentials uc where uc.openId = :openId" );
    query.setParameter( "openId", openId );
    return query.uniqueResult();
}
 
Example 9
Source File: ArtifactPathMigrationUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static Long getArtifactEntityCount() {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query =
        session.createQuery(
            "SELECT count(*) FROM ArtifactEntity ae WHERE ae."
                + ModelDBConstants.STORE_TYPE_PATH
                + " IS NULL");
    return (Long) query.uniqueResult();
  }
}
 
Example 10
Source File: DatasetVersionDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private boolean checkDatasetVersionAlreadyExist(
    Session session, DatasetVersion newDatasetVersion) {
  Query query = session.createQuery(DATASET_VERSION_EXISTS_QUERY);
  query.setParameter("datasetId", newDatasetVersion.getDatasetId());
  query.setParameter("version", newDatasetVersion.getVersion());
  Long count = (Long) query.uniqueResult();
  return count > 0;
}
 
Example 11
Source File: EventDAOHibernate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public long getPendingNotificationCount(Long lessonId, Integer userId) {
String query = EventDAOHibernate.COUNT_PENDING_NOTIFICATIONS;
if (lessonId != null) {
    query += " AND s.event.eventSessionId = :lessonId";
}
Query queryObject = getSession().createQuery(query);
queryObject.setParameter("userId", userId);
if (lessonId != null) {
    queryObject.setParameter("lessonId", lessonId);
}
return (Long) queryObject.uniqueResult();
   }
 
Example 12
Source File: UserPhasesDao.java    From butterfly with Apache License 2.0 5 votes vote down vote up
/**
 * Get the phases for a particular user.
 * @param user
 * @return
 */
public UserPhases getPhasesForUser(final ButterflyUser user) {
    final Query<UserPhases> query = this.getCurrentSession().createQuery("from UserPhases p where p.user = :user");
    query.setParameter("user", user);

    return query.uniqueResult();
}
 
Example 13
Source File: AssessmentResultDAOHibernate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public Float getAvergeTotalScoreByUser(Long sessionId, Long userId) {
Query<Double> q = getSession().createQuery(AVERAGE_SCORE_BY_SESSION_AND_USER, Double.class);
q.setParameter("userId", userId);
q.setParameter("sessionId", sessionId);
Double result = q.uniqueResult();
return result == null ? null : result.floatValue();
   }
 
Example 14
Source File: HibernateUserCredentialsStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public UserCredentials getUserCredentialsByLdapId( String ldapId )
{
    Query<UserCredentials> query = getQuery( "from UserCredentials uc where uc.ldapId = :ldapId" );
    query.setParameter( "ldapId", ldapId );
    return query.uniqueResult();
}
 
Example 15
Source File: HibernateAnalyticalObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public long countAnalyticalObjects( CategoryOptionGroup categoryOptionGroup )
{
    Query<Long> query = getTypedQuery( "select count(distinct c) from " + clazz.getName()
        + " c where :categoryOptionGroup in elements(c.categoryOptionGroups)" );
    query.setParameter( "categoryOptionGroup", categoryOptionGroup );
    return query.uniqueResult();
}
 
Example 16
Source File: HibernateInterpretationStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Interpretation getByVisualizationId( long id )
{
    String hql = "from Interpretation i where i.visualization.id = " + id;
    Query<Interpretation> query = getQuery( hql );
    return query.uniqueResult();
}
 
Example 17
Source File: HibernateAnalyticalObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public long countAnalyticalObjects( DataSet dataSet )
{
    Query<Long> query = getTypedQuery( "select count(distinct c) from " + clazz.getName()
        + " c join c.dataDimensionItems d where d.dataSet = :dataSet" );
    query.setParameter( "dataSet", dataSet );
    return query.uniqueResult();
}
 
Example 18
Source File: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public static void checkIfEntityAlreadyExists(
    Session session,
    String shortName,
    String command,
    String entityName,
    String fieldName,
    String name,
    String workspaceColumnName,
    String workspaceId,
    WorkspaceType workspaceType,
    Logger logger) {
  Query query =
      getWorkspaceEntityQuery(
          session,
          shortName,
          command,
          fieldName,
          name,
          workspaceColumnName,
          workspaceId,
          workspaceType,
          true,
          null);
  Long count = (Long) query.uniqueResult();

  if (count > 0) {
    // Throw error if it is an insert request and project with same name already exists
    logger.info(entityName + " with name {} already exists", name);
    Status status =
        Status.newBuilder()
            .setCode(Code.ALREADY_EXISTS_VALUE)
            .setMessage(entityName + " already exists in database")
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example 19
Source File: HibernateAnalyticalObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public long countAnalyticalObjects( Indicator indicator )
{
    Query<Long> query = getTypedQuery( "select count(distinct c) from " + clazz.getName()
        + " c join c.dataDimensionItems d where d.indicator = :indicator" );
    query.setParameter( "indicator", indicator );
    return query.uniqueResult();
}
 
Example 20
Source File: HibernateMessageConversationStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public long getUnreadUserMessageConversationCount( User user )
{
    Assert.notNull( user, "User must be specified" );

    String hql = "select count(*) from MessageConversation m join m.userMessages u where u.user = :user and u.read = false";

    Query<Long> query = getTypedQuery( hql );
    query.setParameter( "user", user );

    return query.uniqueResult();
}