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

The following examples show how to use org.hibernate.query.Query#executeUpdate() . 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: ExperimentDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Experiment deleteArtifacts(String experimentId, String artifactKey)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();

    Query query = session.createQuery(DELETE_ARTIFACT_QUERY);
    query.setParameter("keys", Collections.singletonList(artifactKey));
    query.setParameter(ModelDBConstants.EXPERIMENT_ID_STR, experimentId);
    query.executeUpdate();
    ExperimentEntity experimentObj = session.get(ExperimentEntity.class, experimentId);
    experimentObj.setDate_updated(Calendar.getInstance().getTimeInMillis());
    session.update(experimentObj);
    transaction.commit();
    return experimentObj.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteArtifacts(experimentId, artifactKey);
    } else {
      throw ex;
    }
  }
}
 
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 setSingleRoomAsDirtyByRoomNumber(String roomNumber) {
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<?> query = session.createQuery("UPDATE Room SET cleaningStatus = 'DIRTY' where number=:roomNumber");
        query.setParameter("roomNumber", roomNumber);
        query.executeUpdate();
        
        logging.setMessage("RoomDaoImpl -> room number :"+roomNumber+" status updated to dirty successfully.");
        
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
    }
    session.close();
}
 
Example 3
Source File: CommentDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean deleteComment(
    String entityType, String entityId, String commentId, UserInfo userInfo) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    String finalQuery = DELETE_USER_COMMENTS_QUERY;
    if (userInfo != null) {
      finalQuery = finalQuery + " AND uc." + ModelDBConstants.OWNER + " = :vertaId";
    }
    Query query = session.createQuery(finalQuery);
    query.setParameter("id", commentId);
    if (userInfo != null) {
      query.setParameter("vertaId", authService.getVertaIdFromUserInfo(userInfo));
    }
    Transaction transaction = session.beginTransaction();
    query.executeUpdate();
    transaction.commit();
    LOGGER.debug("Comments deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteComment(entityType, entityId, commentId, userInfo);
    } else {
      throw ex;
    }
  }
}
 
Example 4
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 setAllRoomsAtDirty(String dirty) {

    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<?> query = session.createQuery("UPDATE Room SET cleaningStatus=:dirty");
        query.setParameter("dirty", dirty);
        query.executeUpdate();
        
        logging.setMessage("RoomDaoImpl -> all rooms status updated to dirty successfully.");
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
    }
    session.close();
}
 
Example 5
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 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: RoomDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setAllRoomsAtClean(String clean) {

    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<?> query = session.createQuery("UPDATE Room SET cleaningStatus=:clean");
        query.setParameter("clean", clean);
        query.executeUpdate();
        
        logging.setMessage("RoomDaoImpl -> All rooms status updated to clean successfully.");
        
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
    }
    session.close();
}
 
Example 8
Source File: PostingDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean deletePosting(long theId) {

    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<?> query = session.createQuery("delete Posting where id = :theId");
        query.setParameter("theId", theId);
        query.executeUpdate();

        logging.setMessage("PostingDaoImpl -> posting deleted successfully.");
        return true;

    } catch (HibernateException e) {
        session.getTransaction().rollback();
        logging.setMessage("PostingDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return false;
}
 
Example 9
Source File: DefaultIssueManager.java    From onedev with MIT License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Transactional
@Override
public void fixFieldValueOrders() {
	Query query = getSession().createQuery("select distinct name, value, ordinal from IssueField where type=:choice");
	query.setParameter("choice", FieldSpec.ENUMERATION);

	for (Object[] row: (List<Object[]>)query.getResultList()) {
		String name = (String) row[0];
		String value = (String) row[1];
		long ordinal = (long) row[2];
		SpecifiedChoices specifiedChoices = SpecifiedChoices.of(getIssueSetting().getFieldSpec(name));
		if (specifiedChoices != null) {
			long newOrdinal = specifiedChoices.getChoiceValues().indexOf(value);
			if (ordinal != newOrdinal) {
				query = getSession().createQuery("update IssueField set ordinal=:newOrdinal where name=:fieldName and value=:fieldValue");
				query.setParameter("fieldName", name);
				query.setParameter("fieldValue", value);
				query.setParameter("newOrdinal", newOrdinal);
				query.executeUpdate();
			}
		}
	}
}
 
Example 10
Source File: RepositoryDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public void deleteBranchByCommit(Session session, Long repoId, String commitHash) {
  StringBuilder deleteBranchesHQLBuilder =
      new StringBuilder("DELETE FROM ")
          .append(BranchEntity.class.getSimpleName())
          .append(" br where br.id.repository_id = :repositoryId ")
          .append(" AND br.commit_hash = :commitHash ");
  Query deleteBranchQuery = session.createQuery(deleteBranchesHQLBuilder.toString());
  deleteBranchQuery.setParameter("repositoryId", repoId);
  deleteBranchQuery.setParameter("commitHash", commitHash);
  deleteBranchQuery.executeUpdate();
}
 
Example 11
Source File: ExperimentDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean deleteExperiments(List<String> experimentIds) {
  List<String> accessibleExperimentIds =
      getAccessibleExperimentIDs(experimentIds, ModelDBActionEnum.ModelDBServiceActions.UPDATE);

  if (accessibleExperimentIds.isEmpty()) {
    String errorMessage =
        "Access is denied. User is unauthorized for given Experiment IDs : "
            + accessibleExperimentIds;
    ModelDBUtils.logAndThrowError(
        errorMessage,
        Code.PERMISSION_DENIED_VALUE,
        Any.pack(DeleteExperiments.getDefaultInstance()));
  }

  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    Query deletedExperimentQuery = session.createQuery(DELETED_STATUS_EXPERIMENT_QUERY_STRING);
    deletedExperimentQuery.setParameter("deleted", true);
    deletedExperimentQuery.setParameter("experimentIds", accessibleExperimentIds);
    int updatedCount = deletedExperimentQuery.executeUpdate();
    LOGGER.debug(
        "Mark Experiments as deleted : {}, count : {}", accessibleExperimentIds, updatedCount);
    transaction.commit();
    LOGGER.debug("Experiment deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteExperiments(experimentIds);
    } else {
      throw ex;
    }
  }
}
 
Example 12
Source File: HibernatePersistentObjectDAO.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public int bulkUpdate(String expression, Object[] values) throws PersistenceException {
	if (!checkStoringAspect())
		return 0;

	try {
		Query queryObject = prepareQueryForUpdate("update " + entityClass.getCanonicalName() + " " + expression,
				values, null);
		return queryObject.executeUpdate();
	} catch (Throwable e) {
		throw new PersistenceException(e);
	}
}
 
Example 13
Source File: RoomDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 5 votes vote down vote up
public void setRoomAsDefaultByRoomNumber(String theNumber) {

        try {
            session = dataSourceFactory.getSessionFactory().openSession();
            beginTransactionIfAllowed(session);

            Query<?> query = session .createQuery("UPDATE Room SET price = :price, totalPrice = :total,"
                    + " balance = :balance, cleaningStatus = :clnSts, usageStatus = :usgSts, "
                    + "personCount = :prsnCnt, customerGroupName = :groupName, ReservationId = :reservId, "
                    + "currency = :currency, remainingDebt = :debt WHERE number = :theNumber");
            
            query.setParameter("price", 0);
            query.setParameter("total", "0");
            query.setParameter("balance", "0");
            query.setParameter("clnSts", "CLEAN");
            query.setParameter("usgSts", "EMPTY");
            query.setParameter("prsnCnt", 0);
            query.setParameter("groupName", "");
            query.setParameter("reservId", 0);
            query.setParameter("currency", "TURKISH LIRA");
            query.setParameter("debt", 0);
            query.setParameter("theNumber", theNumber);
            query.executeUpdate();
            session.getTransaction().commit();

            logging.setMessage("RoomDaoImpl -> room number :"+theNumber+" status updated to default successfully.");
            
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
        }
        session.close();
    }
 
Example 14
Source File: MindmapNodeDAO.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public void deleteNodeByUniqueMindmapUser(Long uniqueId, Long mindmapId, Long userId, Long sessionId) {
Session session = getSessionFactory().getCurrentSession();
Query query = session.createQuery(DELETE_NODE_MULTIUSER_MODE)
	.setParameter("unique_id", uniqueId)
	.setParameter("mindmap_id", mindmapId)
	.setParameter("user_id", userId)
	.setParameter("session_id", sessionId);
query.executeUpdate();
   }
 
Example 15
Source File: DeleteEntitiesCron.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private void deleteLabels(Session session, Object entityHash, IDTypeEnum.IDType idType) {
  String deleteLabelsQueryString =
      new StringBuilder("DELETE LabelsMappingEntity lm where lm.id.")
          .append(ModelDBConstants.ENTITY_HASH)
          .append(" = :entityHash ")
          .append(" AND lm.id.")
          .append(ModelDBConstants.ENTITY_TYPE)
          .append(" = :entityType")
          .toString();
  Query deleteLabelsQuery = session.createQuery(deleteLabelsQueryString);
  deleteLabelsQuery.setParameter("entityHash", entityHash);
  deleteLabelsQuery.setParameter("entityType", idType.getNumber());
  deleteLabelsQuery.executeUpdate();
}
 
Example 16
Source File: DefaultMilestoneManager.java    From onedev with MIT License 5 votes vote down vote up
@Transactional
@Override
public void delete(Milestone milestone) {
	Query<?> query = getSession().createQuery("update Issue set milestone=null where milestone=:milestone");
	query.setParameter("milestone", milestone);
	query.executeUpdate();
	super.delete(milestone);
}
 
Example 17
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean deleteExperimentRuns(List<String> experimentRunIds) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {

    List<String> accessibleExperimentRunIds =
        getAccessibleExperimentRunIDs(
            experimentRunIds, ModelDBActionEnum.ModelDBServiceActions.UPDATE);
    if (accessibleExperimentRunIds.isEmpty()) {
      Status statusMessage =
          Status.newBuilder()
              .setCode(Code.PERMISSION_DENIED_VALUE)
              .setMessage(
                  "Access is denied. User is unauthorized for given ExperimentRun entities : "
                      + accessibleExperimentRunIds)
              .build();
      throw StatusProto.toStatusRuntimeException(statusMessage);
    }
    Transaction transaction = session.beginTransaction();
    Query query = session.createQuery(DELETED_STATUS_EXPERIMENT_RUN_QUERY_STRING);
    query.setParameter("deleted", true);
    query.setParameter("experimentRunIds", accessibleExperimentRunIds);
    int updatedCount = query.executeUpdate();
    LOGGER.debug(
        "Mark ExperimentRun as deleted : {}, count : {}",
        accessibleExperimentRunIds,
        updatedCount);
    transaction.commit();
    LOGGER.debug("ExperimentRun deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteExperimentRuns(experimentRunIds);
    } else {
      throw ex;
    }
  }
}
 
Example 18
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteArtifacts(String experimentRunId, String artifactKey) {
  Transaction transaction = null;
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    transaction = session.beginTransaction();

    if (false) { // Change it with parameter for support to delete all artifacts
      Query query = session.createQuery(DELETE_ALL_ARTIFACTS_HQL);
      query.setParameter(ModelDBConstants.EXPERIMENT_RUN_ID_STR, experimentRunId);
      query.executeUpdate();
    } else {
      deleteArtifactEntities(
          session,
          experimentRunId,
          Collections.singletonList(artifactKey),
          ModelDBConstants.ARTIFACTS);
    }
    long currentTimestamp = Calendar.getInstance().getTimeInMillis();
    ExperimentRunEntity experimentRunObj =
        session.get(ExperimentRunEntity.class, experimentRunId);
    experimentRunObj.setDate_updated(currentTimestamp);
    session.update(experimentRunObj);
    transaction.commit();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      deleteArtifacts(experimentRunId, artifactKey);
    } else {
      throw ex;
    }
  }
}
 
Example 19
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean deleteProjects(List<String> projectIds) {

  // Get self allowed resources id where user has delete permission
  List<String> allowedProjectIds =
      roleService.getAccessibleResourceIdsByActions(
          ModelDBServiceResourceTypes.PROJECT, ModelDBServiceActions.DELETE, projectIds);
  if (allowedProjectIds.isEmpty()) {
    Status status =
        Status.newBuilder()
            .setCode(Code.PERMISSION_DENIED_VALUE)
            .setMessage("Delete Access Denied for given project Ids : " + projectIds)
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }

  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    Query deletedProjectQuery = session.createQuery(DELETED_STATUS_PROJECT_QUERY_STRING);
    deletedProjectQuery.setParameter("deleted", true);
    deletedProjectQuery.setParameter("projectIds", allowedProjectIds);
    int updatedCount = deletedProjectQuery.executeUpdate();
    LOGGER.debug("Mark Projects as deleted : {}, count : {}", allowedProjectIds, updatedCount);
    transaction.commit();
    LOGGER.debug("Project deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteProjects(projectIds);
    } else {
      throw ex;
    }
  }
}
 
Example 20
Source File: DatasetDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean deleteDatasets(List<String> datasetIds) {
  // Get self allowed resources id where user has delete permission
  List<String> allowedDatasetIds =
      roleService.getAccessibleResourceIdsByActions(
          ModelDBServiceResourceTypes.DATASET,
          ModelDBActionEnum.ModelDBServiceActions.DELETE,
          datasetIds);
  if (allowedDatasetIds.isEmpty()) {
    Status status =
        Status.newBuilder()
            .setCode(Code.PERMISSION_DENIED_VALUE)
            .setMessage("Access Denied for given dataset Ids : " + datasetIds)
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }

  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    Query deletedDatasetsQuery = session.createQuery(DELETED_STATUS_DATASET_QUERY_STRING);
    deletedDatasetsQuery.setParameter("deleted", true);
    deletedDatasetsQuery.setParameter("datasetIds", allowedDatasetIds);
    int updatedCount = deletedDatasetsQuery.executeUpdate();
    LOGGER.debug("Mark Datasets as deleted : {}, count : {}", allowedDatasetIds, updatedCount);
    transaction.commit();
    LOGGER.debug("Dataset deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteDatasets(datasetIds);
    } else {
      throw ex;
    }
  }
}