Skip to content

Instantly share code, notes, and snippets.

@stefanotroia
Created November 19, 2019 20:14
Show Gist options
  • Save stefanotroia/e196a4c083f0df82b3a8619b7c3d6a2c to your computer and use it in GitHub Desktop.
Save stefanotroia/e196a4c083f0df82b3a8619b7c3d6a2c to your computer and use it in GitHub Desktop.
Base service with generics
@Service
@Slf4j
public class BaseService<E extends BaseEntity> {
@Autowired
protected GenericRepository<E> generalRepo;
public Mono<E> findEnitity(String entityId, String tenantId) {
return generalRepo.findFirstByIdAndTenantId(entityId,tenantId);
}
public Mono<Void> delete(String entityId, String tenantId) {
return findEnitity(entityId, tenantId)
.switchIfEmpty(Mono.error(new NotFoundException(ITEM_NOT_FOUND)))
.flatMap(e -> generalRepo.deleteByIdAndTenantId(e.getId(),e.getTenantId()));
}
public Mono<E> saveEntity(String tenantId, E entity) {
entity.setTenantId(tenantId);
return generalRepo.save(entity);
}
public Mono<E> updateEntity(String entityId, String tenantId,E entity) {
return findEnitity(entityId,tenantId)
.map(u -> saveEntity(tenantId,entity))
.switchIfEmpty(Mono.error(new Exception(ITEM_NOT_FOUND)))
.flatMap(m -> m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment