Understanding the same method in Pository and in service

Asked

Viewed 183 times

1

Why in the service and controller, do objects point to the same function? I’ll detail:

Repository:

@RepositoryRestResource(exported = false)
public interface AtividadeRepository extends CrudRepository<Atividade, Integer> {
    Atividade findByNome(String nome); //até aqui tudo bem.
}

service:

public Iterable<Atividade> findAll() {
   return atividadeRepository.findAll();
}

//Retorna todas as atividades, até aqui tudo bem.

Controller:

@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody ResponseEntity<Iterable<Atividade>> listAll() {
    Iterable<Atividade> atividades;
    atividades = atividadeService.findAll();
    return new ResponseEntity<Iterable<Atividade>>(atividades, HttpStatus.OK);
}

Why in addition to using the same method, has also the return?

Can’t the controller take the Repository object and send it to the view instead of "search" and return? Or the line:

    return new ResponseEntity<Iterable<Atividade>>(atividades, HttpStatus.OK);

only returns status?

I know you have the issue of code reuse, but doing the same search, I find it redundant.

Or am I totally on the outside?

1 answer

1

Why in addition to using the same method, has also the return?

It’s not quite the same method. As you’re using a multilayer application, for this example, it may seem like it’s the same thing, but it’s not.

The repository serves to manipulate collections in some way. The service harmonizes the relationships between different repositories.

The controller cannot take from the object of Repository and send to the view instead of doing the "search" and return?

You can even delete the service layer for this step and eliminate a prolix part, but this would probably make your project out of the pattern, since the service layer can be used in other system steps.

I know you have the issue of code reuse, but doing the same search, I find it redundant.

It’s not just you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.