如何使用spring data mongo更新所有行的特定列

Posted

技术标签:

【中文标题】如何使用spring data mongo更新所有行的特定列【英文标题】:How to update particular column of all rows using spring data mongo 【发布时间】:2017-12-22 01:11:31 【问题描述】:

我有一个租户表,其中一次应该只有一个租户处于活动状态。

要激活租户,我使用以下代码。有没有更好的方法来使用 spring data mongo 更改所有行的特定列。

        tenantRepository.save(tenantRepository.findAll().stream().map(t -> 
            t.setActive(false);
            return t;
        ).collect(Collectors.toList()));

        tenant.setActive(true);
        tenantRepository.save(tenant);

【问题讨论】:

Can Spring Data Mongo update only dirty field in a document?的可能重复 【参考方案1】:

如果您想更新 Spring Data Mongo 中的特定列,只需定义您的自定义存储库接口及其实现,如下所示:

定义自定义接口

public interface TenantRepositoryCustom 

    Integer updateStatus(List<String> id, TenantStatus status, Date date);

实现您的自定义界面

@Repository
public class TenantRepositoryCustomImpl implements TenantRepositoryCustom

    @Autowired
    MongoTemplate template;

    @Override
    Integer updateStatus(List<String> id, TenantStatus status, Date date) 
        WriteResult result = template.updateMulti(new Query(Criteria.where("id").in(ids)),
                new Update().set("status", status).set("sentTime", date), Tenant.class);
        return result.getN();
    

从自定义存储库扩展您的默认租户存储库:

public interface TenantRepository extends MongoRepository<Tenant, String>, TenantRepositoryCustom

在服务中使用自定义存储库

    @Service
    public class TenantService
        @Autowired
        TenantRepository repo;

        public void updateList()
            //repo.updateStatus(...)
        
    

注意:

与使用 @Query 相比,这更不容易出错,因为在这里您只需指定列的名称和值,而不是完整的查询。

【讨论】:

以上是关于如何使用spring data mongo更新所有行的特定列的主要内容,如果未能解决你的问题,请参考以下文章