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 File: PaymentDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@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 2
Source File: RoomDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@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
Source File: DatasetVersionDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@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
Source File: ReservationDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@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
Source File: KickstartFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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
Source File: DefaultPullRequestManager.java    From onedev with 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 7
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 8
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 9
Source File: ActionManagerTest.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
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 10
Source File: HibernateTrackedEntityAttributeValueStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 11
Source File: QueryBuilderConfigDAL.java    From Insights with 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 12
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 13
Source File: DefaultBuildManager.java    From onedev with 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 14
Source File: ToolsLayoutDAL.java    From Insights with 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 15
Source File: UserSongRecordDao.java    From butterfly with 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 16
Source File: AbsSupportDao.java    From jeesupport with 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 17
Source File: DefaultPullRequestManager.java    From onedev with 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 18
Source File: WebHookConfigDAL.java    From Insights with 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 19
Source File: HibernateProgramInstanceStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 20
Source File: ExperimentRunDAORdbImpl.java    From modeldb with 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;
    }
  }
}