Skip to content

Instantly share code, notes, and snippets.

@filipeovercom
Created June 3, 2019 23:24
Show Gist options
  • Save filipeovercom/8f161f47ffc902aecb340ad484e098f8 to your computer and use it in GitHub Desktop.
Save filipeovercom/8f161f47ffc902aecb340ad484e098f8 to your computer and use it in GitHub Desktop.
Serviço abstrato - Spring Boot+MongoDB
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
public abstract class AbstractService<T, ID extends Serializable> implements IBaseService<T, ID> {
private MongoRepository<T, ID> repository;
private MongoTemplate mongoTemplate;
public AbstractService(MongoRepository<T, ID> repository, MongoTemplate mongoTemplate) {
this.repository = repository;
this.mongoTemplate = mongoTemplate;
}
@Override
public Page<T> findAll(Pageable pageable) {
return repository.findAll(pageable);
}
@Override
public Optional<T> findByID(ID id) {
return repository.findById(id);
}
@Override
public T cadastra(T entity) {
return repository.insert(entity);
}
@Override
public void atualiza(T entity) {
Update update = new Update();
Map<String, Object> props = entityToMap(entity);
props.forEach(update::set);
mongoTemplate.updateFirst(
Query.query(Criteria.where("_id").is(((DefaultDocument) entity).getId())),
update, entity.getClass());
}
@Override
public void remove(ID id) {
repository.deleteById(id);
}
private Map<String, Object> entityToMap(T entity) throws IllegalArgumentException {
Class<?> pomclass = entity.getClass();
Map<String, Object> map = new HashMap<>();
Arrays.stream(pomclass.getMethods())
.filter(method -> method.getName().startsWith("get") && !method.getName().startsWith("getClass")
&& !method.getName().startsWith("getId"))
.forEach(method -> {
Object value = null;
try {
value = method.invoke(entity);
} catch (IllegalAccessException | InvocationTargetException ignored) {
}
map.put(method.getName().substring(3), value);
});
map.values().removeIf(Objects::isNull);
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment