TopicosController
package br.com.projeto.forum.controller;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import br.com.projeto.forum.controller.form.TopicoForm;
import br.com.projeto.forum.dto.TopicoDto;
import br.com.projeto.forum.model.Topico;
import br.com.projeto.forum.repository.CursoRepository;
import br.com.projeto.forum.repository.TopicoRepository;
@RestController
@RequestMapping("/topicos")
public class TopicosController {
@Autowired
private TopicoRepository topicoRepository;
@Autowired
private CursoRepository cursoRepository;
@GetMapping
public List<TopicoDto>lista(String nomeCurso){
if (nomeCurso == null) {
List<Topico> topicos = topicoRepository.findAll();
return TopicoDto.converter(topicos);
} else {
List<Topico> topicos = topicoRepository.findByCursoNome(nomeCurso);
return TopicoDto.converter(topicos);
}
}
@PostMapping
public ResponseEntity<TopicoDto> cadastrar(@RequestBody TopicoForm form, UriComponentsBuilder uriBuilder) {
Topico topico = form.converter(cursoRepository);
topicoRepository.save(topico);
URI uri = uriBuilder.path("/topicos/{id}").buildAndExpand(topico.getId()).toUri();
return ResponseEntity.created(uri).body(new TopicoDto(topico));
}
}
interface TopicoRepository
package br.com.projeto.forum.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.projeto.forum.model.Topico;
public interface TopicoRepository extends JpaRepository<Topico, Long> {
List<Topico> findByCursoNome(String nomeCurso);
}