Java Code Examples for org.springframework.data.mongodb.core.query.Update#update()

The following examples show how to use org.springframework.data.mongodb.core.query.Update#update() . 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: TxManagerServiceImpl.java    From Lottor with MIT License 6 votes vote down vote up
/**
 * 更新 TM中的消息状态
 *
 * @param transactionMsg
 */
@Override
public Boolean updateTxTransactionMsgStatus(TransactionMsg transactionMsg) {
    try {
        Query query = new Query();
        query.addCriteria(new Criteria("groupId").is(transactionMsg.getGroupId()).and("subTaskId").is(transactionMsg.getSubTaskId()));
        Update update = Update.update("consumed", transactionMsg.getConsumed());
        String message = transactionMsg.getMessage();
        if (StringUtils.isNotBlank(message)) {
            update.set("message", message);
        }
        update.set("updateTime", Timestamp.valueOf(DateUtils.getCurrentDateTime()).getTime());
        final WriteResult writeResult = mongoTemplate.updateFirst(query, update, TransactionMsg.class, CollectionNameEnum.TransactionMsg.name());
        return writeResult.getN() > 0;
    } catch (Exception e) {
        //TODO 处理异常
        LogUtil.error(LOGGER, e::getLocalizedMessage);
        return false;
    }
}
 
Example 2
Source File: BaseItemServiceImpl.java    From Lottor with MIT License 6 votes vote down vote up
@Override
public int updateItem(BaseItem baseItem) {
    Query query = new Query();
    query.addCriteria(new Criteria("type").is(baseItem.getType()).and("itemId").is(baseItem.getItemId()));
    BaseItem item = mongoTemplate.findOne(query, BaseItem.class, CollectionNameEnum.BaseItem.name());
    if (Objects.isNull(item)) {
        baseItem.setHealthyState(false);
        baseItem.setRetryCount(1);
        baseItem.setLastModified(System.currentTimeMillis());
        mongoTemplate.save(baseItem, collectionName);
        return baseItem.getRetryCount();
    }
    int count = item.getRetryCount();
    Update update = Update.update("retryCount", count + 1);
    update.set("lastModified", System.currentTimeMillis());
    if (count < 1) {
        update.set("healthyState", false);
    }
    mongoTemplate.updateFirst(query, update, BaseItem.class, collectionName);
    return count + 1;
}
 
Example 3
Source File: AuthorServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
@Override
public void upsertAuthorFreq(Long mid, Integer interval, Integer delay) {
    AuthorIntervalRecord preInterval =
            mongoTemplate.findOne(Query.query(Criteria.where("mid").is(mid)),
                    AuthorIntervalRecord.class, "author_interval");
    Calendar nextCal = Calendar.getInstance();
    Date cTime = Calendar.getInstance().getTime();
    nextCal.add(Calendar.SECOND, delay);
    // 更新访问频率数据。
    Update u = Update.update("date", cTime);
    if (preInterval == null || preInterval.getInterval() == null || interval < preInterval.getInterval()) {
        u.set("interval", interval);
    }
    // 如果此前没有访问频率数据,或者更新后的访问时间比原来的访问时间还短,则刷新下次访问的时间。
    if (preInterval == null || preInterval.getNext() == null) {
        u.set("next", cTime);
        logger.info("[UPSERT] 作者:{} 访问频率:{} 下次爬取:{}", mid, interval, cTime);
    } else if (nextCal.getTimeInMillis() < preInterval.getNext().getTime()) {
        u.set("next", nextCal.getTime());
        logger.info("[UPSERT] 作者:{} 访问频率:{} 下次爬取:{}", mid, interval, nextCal.getTime());
    }
    mongoTemplate.upsert(Query.query(Criteria.where("mid").is(mid)), u, AuthorIntervalRecord.class);
}
 
Example 4
Source File: TenantMongoDA.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List<String>> getPreloadFiles() {
    NeutralQuery preloadReadyTenantQuery = new NeutralQuery().addCriteria(
            new NeutralCriteria(STATUS_FIELD, "=", "ready")).setIncludeFields(
            Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, TENANT_ID));
    Update update = Update.update(ALL_STATUS_FIELDS, "started");

    Map<String, List<String>> fileMap = new HashMap<String, List<String>>();
    Entity tenant;
    while ((tenant = entityRepository.findAndUpdate(TENANT_COLLECTION, preloadReadyTenantQuery, update)) != null) {
        LOG.info("Found new tenant to preload! [" + tenant.getBody().get(TENANT_ID) + "]");
        List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE);
        for (Map<String, Object> landingZone : landingZones) {
            List<String> files = new ArrayList<String>();
            Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA);
            if (preloadData != null) {
                files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES));
                fileMap.put((String) landingZone.get(PATH), files);
            }
        }
    }
    return fileMap;
}
 
Example 5
Source File: SysUserServiceTenantTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 更新多条
 */
@Test
public void updateOneTest(){
    Query query = Query.query(Criteria.where("tenant_code").is(null));
    Update update = Update.update("tenant_code", "XYS");
    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, SysUser.class);
    log.info("update 影响行数:"+updateResult.getModifiedCount());
}
 
Example 6
Source File: SysUserServiceTenantTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 更新多条
 */
@Test
public void updateMutTest(){
    Query query = Query.query(Criteria.where("tenant_code").is(null));
    Update update = Update.update("tenant_code", "XYS");
    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, SysUser.class);
    log.info("update 影响行数:"+updateResult.getModifiedCount());
}
 
Example 7
Source File: SysUserServiceTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
     * 更新
     */
    @Test
    public void updateTest(){
        Query query = Query.query(Criteria.where("user_phone").is("50"));
        Update update = Update.update("pos_code", "XYS11023");
//        Update update = Update.update("user_phone", "55").set("pos_code", "XYS11023");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, SysUser.class);
        log.info("update 影响行数:"+updateResult.getModifiedCount());
    }
 
Example 8
Source File: TestMongoJavaConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateFirst() {
    final Query query = Query.query(Criteria.where("title").is("Harry Potter"));
    final Update update = Update.update("title", "Something else");
    mongoOperations.updateFirst(query, update, Book.class);
    // Calling update using query: { "title" : "Harry Potter"} and update: { "$set" : { "title" : "Something else"}} in collection: book
}
 
Example 9
Source File: TestMongoJavaConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateMulti() {
    final Query query = new Query();
    final Update update = Update.update("title", "Using multi");
    mongoOperations.updateMulti(query, update, Book.class);
    // Calling update using query: { } and update: { "$set" : { "title" : "Using multi"}} in collection: book
}
 
Example 10
Source File: TestMongoJavaConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpsert() {
    final Query query = new Query(
            Criteria.where("title").is("To Ill a Mocking Bird")
                    .and("author.firstName").is("Bob")
                    .and("author.lastName").is("Smith"));

    final Update update = Update.update("pageCount", 1);
    mongoOperations.upsert(query, update, Book.class);
    // Calling update using query: { "title" : "To Ill a Mocking Bird" , "author.firstName" : "Bob" , "author.lastName" : "Smith"} and update: { "$set" : { "pageCount" : 1}} in collection: book
}
 
Example 11
Source File: TestMongoXMLConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateFirst() {
    final Query query = Query.query(Criteria.where("title").is("Harry Potter"));
    final Update update = Update.update("title", "Something else");
    mongoOperations.updateFirst(query, update, Book.class);
    // Calling update using query: { "title" : "Harry Potter"} and update: { "$set" : { "title" : "Something else"}} in collection: book
}
 
Example 12
Source File: TestMongoXMLConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateMulti() {
    final Query query = new Query();
    final Update update = Update.update("title", "Using multi");
    mongoOperations.updateMulti(query, update, Book.class);
    // Calling update using query: { } and update: { "$set" : { "title" : "Using multi"}} in collection: book
}
 
Example 13
Source File: TestMongoXMLConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpsert() {
    final Query query = new Query(
            Criteria.where("title").is("To Ill a Mocking Bird")
                    .and("author.firstName").is("Bob")
                    .and("author.lastName").is("Smith"));

    final Update update = Update.update("pageCount", 1);
    mongoOperations.upsert(query, update, Book.class);
    // Calling update using query: { "title" : "To Ill a Mocking Bird" , "author.firstName" : "Bob" , "author.lastName" : "Smith"} and update: { "$set" : { "pageCount" : 1}} in collection: book
}
 
Example 14
Source File: EventServiceImpl.java    From ic with MIT License 5 votes vote down vote up
private void publishEvents(List<Event> sequentialEvents) {
    Preconditions.checkState(!sequentialEvents.isEmpty());
    //发布事件,先将事件hidden改为false,然后发qmq消息
    Long firstId = sequentialEvents.get(0).getId();
    Long lastId = sequentialEvents.get(sequentialEvents.size() - 1).getId();
    Query query = Query.query(Criteria.where("id").gte(firstId).lte(lastId));
    Update update = Update.update("_hidden", false);
    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Event.class);
    Preconditions.checkState(updateResult.wasAcknowledged());
    //getMatchedCount返回的是long,size返回的是int,不能使用equals
    Preconditions.checkState(updateResult.getMatchedCount() == sequentialEvents.size());
    //TODO
    logger.info("publishEvents定时任务发布了事件{}",
            sequentialEvents.stream().map(Event::getId).collect(Collectors.toList()));
}
 
Example 15
Source File: MongoApprovalRepositoryImpl.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Override
public boolean updateExpiresAt(final LocalDateTime expiresAt,
                               final MongoApproval mongoApproval) {
    final Update update = Update.update("expiresAt", expiresAt);

    final UpdateResult updateResult = mongoTemplate.updateFirst(byUserIdAndClientIdAndScope(mongoApproval),
            update,
            MongoApproval.class);

    return updateResult.wasAcknowledged();
}
 
Example 16
Source File: MongoClientDetailsRepositoryImpl.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Override
public boolean updateClientSecret(final String clientId,
                                  final String newSecret) {
    final Query query = Query.query(Criteria.where(ID).is(clientId));

    final Update update = Update.update(CLIENT_SECRET, newSecret);

    final UpdateResult updateResult = mongoTemplate.updateFirst(query, update, MongoClientDetails.class);

    return updateResult.wasAcknowledged();
}