當前位置: 首頁>>代碼示例>>Java>>正文


Java Update類代碼示例

本文整理匯總了Java中org.springframework.data.mongodb.core.query.Update的典型用法代碼示例。如果您正苦於以下問題:Java Update類的具體用法?Java Update怎麽用?Java Update使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Update類屬於org.springframework.data.mongodb.core.query包,在下文中一共展示了Update類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: updateUserChangeEmailField

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
/**
 * update v5: {@link UserDocument} has changed; String-Field 'email' was replaced with custom Type 'Email'.
 * find all user with an email String-value, replace String-Type with Custom-Type and update all UserDocuments.
 * if email-Field is Empty or null, you don't have to update user.
 *
 * @since V6
 */
@ChangeSet(order = "006", id = "updateUserChangeEmailFromStringToCustomClass", author = "admin")
public void updateUserChangeEmailField(final MongoTemplate template) {
  final Criteria isEmptyCriteria = new Criteria().orOperator(Criteria.where("email").is(""), Criteria.where("email").is(null));
  while (true) {
    final UserDocument result = template.findAndModify(new Query(isEmptyCriteria), Update.update("email", new Email()), UserDocument.class);
    if (result == null)
      break;
  }

  /**
   * if email not null -> Field will be cast to specific class and updates will create correct entries
   */
  // final Criteria isNotEmptyCriteria = new Criteria().orOperator(Criteria.where("email").ne(""), Criteria.where("email").ne(null));
  // final List<UserDocument> userDocumentList = template.find(new Query(isNotEmptyCriteria), UserDocument.class);

}
 
開發者ID:nkolytschew,項目名稱:mongobee_migration_example,代碼行數:24,代碼來源:DatabaseChangeLog.java

示例2: updateRetry

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
/**
 * 更改恢複次數
 *
 * @param id              事務id
 * @param retry           恢複次數
 * @param applicationName 應用名稱
 * @return true 成功
 */
@Override
public Boolean updateRetry(String id, Integer retry, String applicationName) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String mongoTableName = RepositoryPathUtils.buildMongoTableName(applicationName);

    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    Update update = new Update();
    update.set("lastTime", DateUtils.getCurrentDateTime());
    update.set("retriedCount", retry);
    final WriteResult writeResult = mongoTemplate.updateFirst(query, update,
            MongoAdapter.class, mongoTableName);
    if (writeResult.getN() <= 0) {
        throw new TransactionRuntimeException("更新數據異常!");
    }
    return Boolean.TRUE;
}
 
開發者ID:yu199195,項目名稱:happylifeplat-transaction,代碼行數:28,代碼來源:MongoRecoverTransactionServiceImpl.java

示例3: assignRole

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
@PostMapping("/users/{userId}/roles/{role}")
void assignRole(@PathVariable String userId,
                @PathVariable String role,
                Authentication auth) {

    if (can(auth, "ASSIGN", role)) {
        final Role found = findRoleByName(role);
        if (found == null) throw new RoleNotFoundException();

        if (!mongo.updateFirst(
                query(where("id").is(userId)),
                new Update().addToSet("roles", found),
                User.class
            ).isUpdateOfExisting()) {

            throw new UserNotFoundException();
        }
    } else {
        throw new OperationNotAllowedException();
    }
}
 
開發者ID:membaza,項目名稱:users-service,代碼行數:22,代碼來源:RoleController.java

示例4: revokeRole

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
@DeleteMapping("/users/{userId}/roles/{role}")
void revokeRole(@PathVariable String userId,
                @PathVariable String role,
                Authentication auth) {

    if (can(auth, "REVOKE", role)) {
        final Role found = findRoleByName(role);
        if (found == null) throw new RoleNotFoundException();

        if (!mongo.updateFirst(
            query(where("id").is(userId)),
            new Update().pull("roles", found),
            User.class
        ).isUpdateOfExisting()) {
            throw new UserNotFoundException();
        }
    } else {
        throw new OperationNotAllowedException();
    }
}
 
開發者ID:membaza,項目名稱:users-service,代碼行數:21,代碼來源:RoleController.java

示例5: updateParticipant

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
/**
 * 更新 List<Participant>  隻更新這一個字段數據
 *
 * @param tccTransaction 實體對象
 */
@Override
public int updateParticipant(TccTransaction tccTransaction) {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(tccTransaction.getTransId()));
    Update update = new Update();
    try {
        update.set("contents", objectSerializer.serialize(tccTransaction.getParticipants()));
    } catch (TccException e) {
        e.printStackTrace();
    }
    final WriteResult writeResult = template.updateFirst(query, update, MongoAdapter.class, collectionName);
    if (writeResult.getN() <= 0) {
        throw new TccRuntimeException("更新數據異常!");
    }
    return 1;
}
 
開發者ID:yu199195,項目名稱:happylifeplat-tcc,代碼行數:22,代碼來源:MongoCoordinatorRepository.java

示例6: updateFailTransaction

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
/**
 * 更新事務失敗日誌
 *
 * @param mythTransaction 實體對象
 * @return rows 1 成功
 * @throws MythRuntimeException 異常信息
 */
@Override
public int updateFailTransaction(MythTransaction mythTransaction) throws MythRuntimeException {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(mythTransaction.getTransId()));
    Update update = new Update();

    update.set("status", mythTransaction.getStatus());
    update.set("errorMsg", mythTransaction.getErrorMsg());
    update.set("lastTime", new Date());
    update.set("retriedCount", mythTransaction.getRetriedCount());

    final WriteResult writeResult = template.updateFirst(query, update, MongoAdapter.class, collectionName);
    if (writeResult.getN() <= 0) {
        throw new MythRuntimeException("更新數據異常!");
    }
    return CommonConstant.SUCCESS;
}
 
開發者ID:yu199195,項目名稱:myth,代碼行數:25,代碼來源:MongoCoordinatorRepository.java

示例7: updateParticipant

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
/**
 * 更新 List<Participant>  隻更新這一個字段數據
 *
 * @param mythTransaction 實體對象
 */
@Override
public int updateParticipant(MythTransaction mythTransaction) throws MythRuntimeException {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(mythTransaction.getTransId()));
    Update update = new Update();
    try {
        update.set("contents", objectSerializer.serialize(mythTransaction.getMythParticipants()));
    } catch (MythException e) {
        e.printStackTrace();
    }
    final WriteResult writeResult = template.updateFirst(query, update, MongoAdapter.class, collectionName);
    if (writeResult.getN() <= 0) {
        throw new MythRuntimeException("更新數據異常!");
    }
    return CommonConstant.SUCCESS;
}
 
開發者ID:yu199195,項目名稱:myth,代碼行數:22,代碼來源:MongoCoordinatorRepository.java

示例8: getNextSequenceId

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
public Long getNextSequenceId(String key) {
    /** Get <code>Sequence</code> object by collection name*/
    Query query = new Query(Criteria.where("id").is(key));

    /** Increase field sequence by 1*/
    Update update = new Update();
    update.inc("sequence", 1);

    // указываем опцию, что нужно возвращать измененный объект
    /** Set option about returning new object*/
    FindAndModifyOptions options = new FindAndModifyOptions();
    options.returnNew(true);

    Sequence sequence = mongoOperations.findAndModify(query, update, options, Sequence.class);

    // if no sequence set id value 'key'
    if (sequence == null) {
        sequence = setSequenceId(key, 1L);
    }

    return sequence.getCurrent();
}
 
開發者ID:chirkovd,項目名稱:spring-es-sample,代碼行數:23,代碼來源:SequenceService.java

示例9: saveResourcePlan

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
@Override
public boolean saveResourcePlan(ResourcePlan resourcePlan) {
    boolean result = false;
    if(resourcePlan.getAddTime() == 0) { //insert
        resourcePlan.setAddTime(new Date().getTime());
        resourcePlan.setModTime(new Date().getTime());

        mongoTemplate.save(resourcePlan, Constant.COL_NAME_RESOURCE_PLAN);
        result = Preconditions.isNotBlank(resourcePlan.getId());

    } else {                            //update
        Query query = new Query().addCriteria(Criteria.where("_id").is(resourcePlan.getId()));
        Update update = new Update();
        update.set("startPageNum", resourcePlan.getStartPageNum());
        update.set("endPageNum", resourcePlan.getEndPageNum());
        update.set("modTime", new Date().getTime());

        WriteResult writeResult = mongoTemplate.updateFirst(query, update, Constant.COL_NAME_RESOURCE_PLAN);
        result = writeResult!=null && writeResult.getN() > 0;
    }

    return result;
}
 
開發者ID:fengzhizi715,項目名稱:ProxyPool,代碼行數:24,代碼來源:ProxyResourceDaoImpl.java

示例10: updateNotebook

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
public void updateNotebook(Notebook notebook){
    Query query = new Query();
    query.addCriteria(new Criteria("NotebookId").is(notebook.getNotebookId()));
    Update update = new Update();
    update.set("title", notebook.getTitle());
    update.set("description", notebook.getDescription());
    update.set("creator", notebook.getCreator());
    update.set("owner", notebook.getOwner());
    update.set("star", notebook.getStar());
    update.set("collected", notebook.getCollected());
    update.set("clickCount", notebook.getClickCount());
    update.set("collaborators", notebook.getCollaborators());
    update.set("contributors", notebook.getContributors());
    update.set("notes", notebook.getNotes());
    update.set("createTime", notebook.getCreateTime());
    update.set("cover", notebook.getCover());
    update.set("tags", notebook.getTags());
    update.set("starers", notebook.getStarers());
    mongoTemplate.updateFirst(query, update, Notebook.class,"Notebook");
}
 
開發者ID:qinjr,項目名稱:TeamNote,代碼行數:21,代碼來源:NotebookDaoImpl.java

示例11: updateUser

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
public void updateUser(User user){
    Query query = new Query();
    query.addCriteria(new Criteria("userId").is(user.getUserId()));
    Update update = new Update();
    update.set("username", user.getUsername());
    update.set("personalStatus", user.getPersonalStatus());
    update.set("notebooks", user.getNotebooks());
    update.set("followers", user.getFollowers());
    update.set("followings", user.getFollowings());
    update.set("tags", user.getTags());
    update.set("avatar", user.getAvatar());
    update.set("collections", user.getCollections());
    update.set("valid", user.getValid());
    update.set("deleteCount", user.getDeleteTime());
    update.set("reputation", user.getReputation());
    update.set("qrcode", user.getQrcode());
    mongoTemplate.updateFirst(query, update, User.class,"User");
}
 
開發者ID:qinjr,項目名稱:TeamNote,代碼行數:19,代碼來源:UserDaoImpl.java

示例12: createPasswordRecoveryToken

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
public SmartiUser createPasswordRecoveryToken(String login) {
    final SmartiUser mongoUser = findUser(login);
    if (mongoUser == null) {
        return null;
    }

    final Date now = new Date(),
            expiry = DateUtils.addHours(now, 24);
    final String token = HashUtils.sha256(UUID.randomUUID() + mongoUser.getLogin());
    final SmartiUser.PasswordRecovery recovery = new SmartiUser.PasswordRecovery(token, now, expiry);

    final WriteResult result = updateMongoUser(mongoUser.getLogin(), Update.update(SmartiUser.FIELD_RECOVERY, recovery));
    if (result.getN() == 1) {
        return getSmaritUser(mongoUser.getLogin());
    } else {
        return null;
    }
}
 
開發者ID:redlink-gmbh,項目名稱:smarti,代碼行數:19,代碼來源:MongoUserDetailsService.java

示例13: updateMessage

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
@Override
public Conversation updateMessage(ObjectId conversationId, Message message) {
    final Query query = new Query(Criteria.where("_id").is(conversationId))
            .addCriteria(Criteria.where("messages._id").is(message.getId()));

    final Update update = new Update()
            .set("messages.$", message)
            .currentDate("lastModified");

    final WriteResult writeResult = mongoTemplate.updateFirst(query, update, Conversation.class);
    if (writeResult.getN() == 1) {
        return mongoTemplate.findById(conversationId, Conversation.class);
    } else {
        return null;
    }
}
 
開發者ID:redlink-gmbh,項目名稱:smarti,代碼行數:17,代碼來源:ConversationRepositoryImpl.java

示例14: saveIfNotLastModifiedAfter

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
@Override
public Conversation saveIfNotLastModifiedAfter(Conversation conversation, Date lastModified) {
    
    final Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(conversation.getId()));
    query.addCriteria(Criteria.where("lastModified").lte(lastModified));

    BasicDBObject data = new BasicDBObject();
    mongoTemplate.getConverter().write(conversation, data);
    final Update update = new Update();
    data.entrySet().stream()
        .filter(e -> !Objects.equals("lastModified", e.getKey()))
        .forEach(e -> update.set(e.getKey(), e.getValue()));
    update.currentDate("lastModified");

    final WriteResult writeResult = mongoTemplate.updateFirst(query, update, Conversation.class);
    if (writeResult.getN() == 1) {
        return mongoTemplate.findById(conversation.getId(), Conversation.class);
    } else {
        throw new ConcurrentModificationException(
                String.format("Conversation %s has been modified after %tF_%<tT.%<tS (%tF_%<tT.%<tS)", conversation.getId(), lastModified, conversation.getLastModified()));
    }
}
 
開發者ID:redlink-gmbh,項目名稱:smarti,代碼行數:24,代碼來源:ConversationRepositoryImpl.java

示例15: save

import org.springframework.data.mongodb.core.query.Update; //導入依賴的package包/類
public Document save(String id, Document document) {
	Document _documentUpdate = findById(id);
	if(null==_documentUpdate){
		mongoTemplate.insert(document);
	}else{
		Query query = query(where("documentId").is(id));
		Update update = new Update();
		update.set("name",null == document.getName() ? 
				_documentUpdate.getName():document.getName());
		update.set("location",null == document.getLocation() ? 
				_documentUpdate.getLocation():document.getLocation());
		update.set("description",null == document.getDescription() ? 
				_documentUpdate.getDescription() : document.getDescription());
		update.set("type",null == document.getType() ?
				_documentUpdate.getType() : document.getType());
		update.set("modified", new Date());
		mongoTemplate.updateFirst(query, update, Document.class);
		document = findById(id);
	}
	return document;
}
 
開發者ID:Apress,項目名稱:introducing-spring-framework,代碼行數:22,代碼來源:MongoDocumentRespository.java


注:本文中的org.springframework.data.mongodb.core.query.Update類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。