如何使用 spring 数据 mongo 更新所有行的特定列
How to update particular column of all rows using spring data mongo
我的租户 table 一次只能有一个租户处于活动状态。
要激活租户,我使用以下代码。有没有更好的方法来使用 spring 数据 mongo.
更改所有行的特定列
tenantRepository.save(tenantRepository.findAll().stream().map(t -> {
t.setActive(false);
return t;
}).collect(Collectors.toList()));
tenant.setActive(true);
tenantRepository.save(tenant);
如果您想更新 Spring 数据 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 相比,这更不容易出错,因为在这里您只需指定列的名称和值,而不是完整的查询。
我的租户 table 一次只能有一个租户处于活动状态。
要激活租户,我使用以下代码。有没有更好的方法来使用 spring 数据 mongo.
更改所有行的特定列 tenantRepository.save(tenantRepository.findAll().stream().map(t -> {
t.setActive(false);
return t;
}).collect(Collectors.toList()));
tenant.setActive(true);
tenantRepository.save(tenant);
如果您想更新 Spring 数据 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 相比,这更不容易出错,因为在这里您只需指定列的名称和值,而不是完整的查询。