Reputation: 16671
I have Tenant table where only one tenant should be active at a time.
To activate a tenant i am using following code. Is there a better way to change particular column of all rows using spring data mongo.
tenantRepository.save(tenantRepository.findAll().stream().map(t -> {
t.setActive(false);
return t;
}).collect(Collectors.toList()));
tenant.setActive(true);
tenantRepository.save(tenant);
Upvotes: 0
Views: 1768
Reputation: 6932
If you want to update specific column(s) in Spring data Mongo, simply define your custom repository interface and its implementation like:
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(...)
}
}
This is less error prone as compared to using @Query, as here you will have to just specify column's names and values instead of complete query.
Upvotes: 1