0

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);
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212
  • Possible duplicate of [Can Spring Data Mongo update only dirty field in a document?](https://stackoverflow.com/questions/13397833/can-spring-data-mongo-update-only-dirty-field-in-a-document) – Orest Jul 17 '17 at 14:43

1 Answers1

1

If you want to update specific column(s) in Spring data Mongo, simply define your custom repository interface and its implementation like:

Define Custom Interface

public interface TenantRepositoryCustom {

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

Implement your Custom Interface

@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();
    }

Extends you Default Tenant Repository from Custom Repository:

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

Use Custom repository in Service

    @Service
    public class TenantService{
        @Autowired
        TenantRepository repo;

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

Note:

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.

Afridi
  • 6,753
  • 2
  • 18
  • 27