Saurabh Kumar
Saurabh Kumar

Reputation: 16671

How to update particular column of all rows using spring data mongo

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

Answers (1)

Afridi
Afridi

Reputation: 6932

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.

Upvotes: 1

Related Questions