This project offers a set of classes and annotations to implement soft delete in MongoDB
In order to introduce soft delete in your Spring Boot application with MongoDB, you have to:
- Instantiate in a configuration class the bean CustomMongoTemplate and give to the bean the name mongoTemplate:
import com.giavarone.mongodbsoftdelete.client.CustomMongoTemplate;
@Configuration
public class MyProjectConfiguration {
@Bean("mongoTemplate")
public CustomMongoTemplate customMongoTemplate(MongoDatabaseFactory databaseFactory, MappingMongoConverter converter) {
return new CustomMongoTemplate(databaseFactory, converter);
}
}
- Add the following key-value to your application.properties
spring.main.allow-bean-definition-overriding=true
This way Spring Boot won't throw any exception on startup as we're going to override the default mongoTemplate bean instance 3. Make your model classes extend SoftDelete
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "examples")
public class Example extends SoftDelete {
private Long id;
private String aString;
private Integer aNumber;
}
- In repositories, you can annotate methods with @IncludeDeletedRecords to retrieve soft deleted records too
@Repository
public interface ExampleRepository extends MongoRepository<Example, Long> {
List<Example> findByaString(String aString);
@IncludeDeletedRecords
List<Example> findByaNumber(Integer aNumber);
}
- In your services class, implement delete method like this:
@Service
public class ExampleService {
@Autowired
private ExampleRepository exampleRepository;
public Example findById(Long id) {
return exampleRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("id not valid"));
}
public Example save(Example example) {
return exampleRepository.save(example);
}
public Example update(Long id, Example example) {
Example _example = findById(id);
_example.setAString(example.getAString());
_example.setANumber(example.getANumber());
_example.setDeletedAt(example.getDeletedAt());
return exampleRepository.save(_example);
}
public void delete(Long id) {
Example example = findById(id);
example.setDeletedAt(LocalDateTime.now());
update(id, example);
}
}
- Finally add in your main class the annotation @EnableMongoRepositories this way:
@SpringBootApplication
@EnableMongoRepositories(repositoryFactoryBeanClass = SoftDeleteMongoRepositoryFactoryBean.class)
public class MongoDbSoftDeleteApplication {
public static void main(String[] args) {
SpringApplication.run(MongoDbSoftDeleteApplication.class, args);
}
}
- The development of the project was inspired by this answer on StackOverflow.