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

The following examples show how to use org.hibernate.query.Query#setParameter() . 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 Project: onedev   File: DefaultPullRequestManager.java    License: MIT License 6 votes vote down vote up
@Transactional
@Listen
public void on(EntityRemoved event) {
	if (event.getEntity() instanceof Project) {
		Project project = (Project) event.getEntity();
    	for (PullRequest request: project.getOutgoingRequests()) {
    		if (!request.getTargetProject().equals(project) && request.isOpen())
        		discard(request, "Source project is deleted.");
    	}
    	
    	Query<?> query = getSession().createQuery("update PullRequest set sourceProject=null where "
    			+ "sourceProject=:project");
    	query.setParameter("project", project);
    	query.executeUpdate();
	}
}
 
Example 2
@Override
public void setSingleRoomAsDNDByRoomNumber(String roomNumber) {

    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<?> query = session.createQuery("UPDATE Room SET cleaningStatus = 'DND' where number=:roomNumber");
        query.setParameter("roomNumber", roomNumber);
        query.executeUpdate();
        
        logging.setMessage("RoomDaoImpl -> room number :"+roomNumber+" status updated to dnd successfully.");
        
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
    }
    session.close();

}
 
Example 3
@Override
public Boolean deleteDatasetVersions(List<String> datasetVersionIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    Query deletedDatasetVersionQuery =
        session.createQuery(UPDATE_DELETED_STATUS_DATASET_VERSION_QUERY_STRING);
    deletedDatasetVersionQuery.setParameter("deleted", true);
    deletedDatasetVersionQuery.setParameter("datasetVersionIds", datasetVersionIds);
    int updatedCount = deletedDatasetVersionQuery.executeUpdate();
    LOGGER.debug(
        "Mark DatasetVersions as deleted : {}, count : {}", datasetVersionIds, updatedCount);
    transaction.commit();
    LOGGER.debug("DatasetVersion deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteDatasetVersions(datasetVersionIds);
    } else {
      throw ex;
    }
  }
}
 
Example 4
@Override
public List<Reservation> getReservListByThisDate(String today) {
    List<Reservation> reservationsList = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Reservation> query = session.createQuery("from Reservation where checkinDate=:today", Reservation.class);
        query.setParameter("today", today);
        reservationsList = query.getResultList();

        logging.setMessage("ReservationDaoImpl -> fetching all reservations by date...");

    } catch (NoResultException e) {
        final InformationFrame frame = new InformationFrame();
        frame.setMessage("No reservation found!");
        frame.setVisible(true);
    } finally {
        session.close();
    }
    return reservationsList;
}
 
Example 5
/**
 * Set the kickstart session history message.
 *
 * Java version of the stored procedure set_ks_session_history_message. This procedure
 * attempted to iterate all states with the given label, but these are unique and
 * this method will not attempt to do the same.
 *
 * @param ksSession
 * @param stateLabel
 */
// TODO: Find a better location for this method.
private static void setKickstartSessionHistoryMessage(KickstartSession ksSession,
        KickstartSessionState state, String message) {
    Session session = HibernateFactory.getSession();
    Query q = session.getNamedQuery(
            "KickstartSessionHistory.findByKickstartSessionAndState");
    q.setParameter("state", state);
    q.setParameter("kickstartSession", ksSession);
    List results = q.list();
    Iterator iter = results.iterator();
    while (iter.hasNext()) {
        KickstartSessionHistory history = (KickstartSessionHistory)iter.next();
        history.setMessage(message);
    }

    ksSession.addHistory(state, message);
}
 
Example 6
@Override
public String getTotalCashLiraPaymentsForOneDay(String date) {
    String totalCash = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery("select sum(price) from Payment where "
                + "paymentType = 'CASH PAYMENT' and currency = 'TURKISH LIRA' and dateTime >= :date", String.class);
        query.setParameter("date", date);
        totalCash = query.getSingleResult();

        logging.setMessage("PaymentDaoImpl -> fetching total cash lira for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCash;
}
 
Example 7
@Override
public List<ProgramInstance> getByType( ProgramType type )
{
    String hql = "from ProgramInstance pi where pi.program.programType = :type";

    Query<ProgramInstance> query = getQuery( hql );
    query.setParameter( "type", type );

    return query.list();
}
 
Example 8
Source Project: Insights   File: WebHookConfigDAL.java    License: Apache License 2.0 5 votes vote down vote up
public String deleteWebhookConfigurations(String webhookName) {
	Query<WebHookConfig> createQuery = getSession()
			.createQuery("FROM WebHookConfig a WHERE a.webhookName = :webhookName", WebHookConfig.class);
	createQuery.setParameter("webhookName", webhookName);
	WebHookConfig webhookConfig = createQuery.getSingleResult();
	getSession().beginTransaction();
	getSession().delete(webhookConfig);
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return PlatformServiceConstants.SUCCESS;
}
 
Example 9
Source Project: onedev   File: DefaultPullRequestManager.java    License: MIT License 5 votes vote down vote up
@Transactional
@Override
public void open(PullRequest request) {
	Preconditions.checkArgument(request.isNew());
	
	request.setNumberScope(request.getTargetProject().getForkRoot());
	Query<?> query = getSession().createQuery(String.format("select max(%s) from PullRequest where %s=:numberScope", 
			PullRequest.PROP_NUMBER, PullRequest.PROP_NUMBER_SCOPE));
	query.setParameter("numberScope", request.getNumberScope());
	request.setNumber(getNextNumber(request.getNumberScope(), query));
	
	PullRequestOpened event = new PullRequestOpened(request);
	request.setLastUpdate(event.getLastUpdate());
	
	dao.persist(request);
	request.writeBaseRef();
	request.writeHeadRef();
	
	for (PullRequestUpdate update: request.getUpdates())
		pullRequestUpdateManager.save(update);
	
	pullRequestReviewManager.saveReviews(request);
	pullRequestVerificationManager.saveVerifications(request);
	
	for (PullRequestAssignment assignment: request.getAssignments())
		pullRequestAssignmentManager.save(assignment);

	checkAsync(Lists.newArrayList(request));
	
	listenerRegistry.post(event);
}
 
Example 10
Source Project: jeesupport   File: AbsSupportDao.java    License: MIT License 5 votes vote down vote up
private void _set_parameter( Query _query, String[] _param, Object[] _value ){
	if ( _param != null && _value != null ) {
		for( int i = 0; i < _param.length; i ++ ){
			if( _value[i] instanceof Collection )
				_query.setParameterList( _param[i] , ( Collection<?> ) _value[i] );
			else
				_query.setParameter( _param[i] ,_value[i] );
		}
	}
}
 
Example 11
Source Project: butterfly   File: UserSongRecordDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the latest score for a given user, so we can make sure they start on the last song they played
 * @param user The user of the records
 * @return The latest record
 */
public UserSongRecord findLatestScoreForUser(final UserProfile user) {
    final Query<UserSongRecord> query = this.getCurrentSession().createQuery(
            "from UserSongRecord r where r.user = :user order by r.endtime desc")
            .setMaxResults(1);
    query.setParameter("user", user);

    return query.uniqueResult();
}
 
Example 12
@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 13
Source Project: Insights   File: ToolsLayoutDAL.java    License: Apache License 2.0 5 votes vote down vote up
public boolean deleteToolLayout(String toolName, String toolCategory, int agentId) {
	Query<ToolsLayout> createQuery = getSession().createQuery(
			"FROM ToolsLayout TL WHERE TL.toolName = :toolName AND TL.toolCategory = :toolCategory",
			ToolsLayout.class);
	createQuery.setParameter("toolName", toolName);
	createQuery.setParameter("toolCategory", toolCategory);
	ToolsLayout toolLayout = createQuery.getSingleResult();
	getSession().beginTransaction();
	getSession().delete(toolLayout);
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return true;
}
 
Example 14
Source Project: onedev   File: DefaultBuildManager.java    License: MIT License 5 votes vote down vote up
@Transactional
@Override
public void create(Build build) {
	Preconditions.checkArgument(build.isNew());
	build.setNumberScope(build.getProject().getForkRoot());
	Query<?> query = getSession().createQuery(String.format("select max(%s) from Build where %s=:numberScope", 
			Build.PROP_NUMBER, Build.PROP_NUMBER_SCOPE));
	query.setParameter("numberScope", build.getNumberScope());
	build.setNumber(getNextNumber(build.getNumberScope(), query));
	save(build);
	for (BuildParam param: build.getParams())
		buildParamManager.save(param);
	for (BuildDependence dependence: build.getDependencies())
		buildDependenceManager.save(dependence);
}
 
Example 15
Source Project: modeldb   File: RepositoryDAORdbImpl.java    License: 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 16
Source Project: Insights   File: QueryBuilderConfigDAL.java    License: Apache License 2.0 5 votes vote down vote up
public boolean deleteQuery(String reportName) {
	Query<QueryBuilderConfig> createQuery = getSession().createQuery(
			"FROM QueryBuilderConfig a WHERE a.reportName = :reportName",
			QueryBuilderConfig.class);
	createQuery.setParameter("reportName", reportName);
	QueryBuilderConfig queryBuilderConfig = createQuery.getSingleResult();
	getSession().beginTransaction();
	getSession().delete(queryBuilderConfig);
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return true;
}
 
Example 17
@Override
public int getCountOfAssignedTEAValues( TrackedEntityAttribute attribute )
{
    Query query = getQuery( "select count(distinct c) from TrackedEntityAttributeValue c where c.attribute = :attribute" );
    query.setParameter( "attribute", attribute );

    return ((Long) query.getSingleResult()).intValue();
}
 
Example 18
public void assertActionsForUser(User user, int expected) throws Exception {
    Session session = HibernateFactory.getSession();
    Query query = session.createQuery("from Action a where a.schedulerUser = :user");
    query.setParameter("user", user);
    List results = query.list();
    int initialSize = results.size();
    assertEquals(expected, initialSize);
}
 
Example 19
@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 20
Source Project: modeldb   File: ExperimentRunDAORdbImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public List<ExperimentRun> getExperimentRuns(List<KeyValue> keyValues)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    StringBuilder stringQueryBuilder = new StringBuilder("From ExperimentRunEntity er where ");
    Map<String, Object> paramMap = new HashMap<>();
    for (int index = 0; index < keyValues.size(); index++) {
      KeyValue keyValue = keyValues.get(index);
      Value value = keyValue.getValue();
      String key = keyValue.getKey();

      switch (value.getKindCase()) {
        case NUMBER_VALUE:
          paramMap.put(key, value.getNumberValue());
          break;
        case STRING_VALUE:
          paramMap.put(key, value.getStringValue());
          break;
        case BOOL_VALUE:
          paramMap.put(key, value.getBoolValue());
          break;
        default:
          Status invalidValueTypeError =
              Status.newBuilder()
                  .setCode(Code.UNIMPLEMENTED_VALUE)
                  .setMessage(
                      "Unknown 'Value' type recognized, valid 'Value' type are NUMBER_VALUE, STRING_VALUE, BOOL_VALUE")
                  .build();
          throw StatusProto.toStatusRuntimeException(invalidValueTypeError);
      }
      stringQueryBuilder.append(" er." + key + " = :" + key);
      if (index < keyValues.size() - 1) {
        stringQueryBuilder.append(" AND ");
      }
    }
    Query query =
        session.createQuery(
            stringQueryBuilder.toString() + " AND er." + ModelDBConstants.DELETED + " = false ");
    for (Map.Entry<String, Object> paramEntry : paramMap.entrySet()) {
      query.setParameter(paramEntry.getKey(), paramEntry.getValue());
    }
    List<ExperimentRunEntity> experimentRunObjList = query.list();
    return RdbmsUtils.convertExperimentRunsFromExperimentRunEntityList(experimentRunObjList);
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRuns(keyValues);
    } else {
      throw ex;
    }
  }
}