Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

Duvida Criando DTO's

Eu estou realizando um projeto a parte para tentar fixar melhor a ideia de DTO, mas estou com uma duvida referente ao Service e ao Controller. O Código está funcionando , mas estou com dificuldade de fazer a logica dos métodos do Service, principalmente o metodo Atualizar. Nas aulas foi realizado o método do Controller.

Classe Produto

@Entity
@Table(name = "tb_produto")
public class Produto implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String descricao;
    private Double preco;
    private String imgUrl;

    @ManyToMany
    @JoinTable(name = "tb_produto_categoria", joinColumns = @JoinColumn(name = "produto_id"), inverseJoinColumns = @JoinColumn(name = "categoria_id"))
    private Set<Categoria> categorias = new HashSet<>(); // necessário já instanciar, garantir que a colecao nao comece
                                                            // nula, tem que ser vazia.
    @OneToMany (mappedBy = "id.produto" )
    private Set<PedidoItem> itens = new HashSet<>();

    public Produto() {

    }

    public Produto(Long id, String nome, String descricao, Double preco, String imgUrl) {
        super();
        this.id = id;
        this.nome = nome;
        this.descricao = descricao;
        this.preco = preco;
        this.imgUrl = imgUrl;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Double getPreco() {
        return preco;
    }

    public void setPreco(Double preco) {
        this.preco = preco;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public Set<Categoria> getCategorias() {
        return categorias;
    }

    @JsonIgnore
    public Set <Pedido> getPedidos(){
        Set<Pedido> set = new HashSet<>();
        for (PedidoItem x: itens ) {
            set.add(x.getPedido());
        }
        return set;

    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Produto other = (Produto) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

}

ProdutoDTO

public class ProdutoDto {
    private String nome;
    private String descricao;
    private Double preco;


    public ProdutoDto() {

    }
    public ProdutoDto(String nome, String descricao, Double preco) {
        super();
        this.nome = nome;
        this.descricao = descricao;
        this.preco = preco;
    }

    public ProdutoDto(Produto produto) {

        this.nome = produto.getNome();
        this.descricao = produto.getDescricao();
        this.preco = produto.getPreco();
    }

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getDescricao() {
        return descricao;
    }
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }
    public Double getPreco() {
        return preco;
    }
    public void setPreco(Double preco) {
        this.preco = preco;
    }
    public static List<ProdutoDto> convert(List<Produto> produtos) {
        return produtos.stream().map(ProdutoDto::new).collect(Collectors.toList());

    }
3 respostas

Classe ProdutoService

@Service
public class ProdutoService {

    @Autowired
    private ProdutoRepository rep;

    public List<Produto> findAll(){
        return rep.findAll();
    }

    public ProdutoDto findById(Long id) {
        Produto obj= rep.findById(id).get();
        ProdutoDto dto = new ProdutoDto(obj);
        return dto;

    }

public Produto inserir(Produto obj) {

        return rep.save(obj);
    }

public void delete (Long id) {
    try {
    rep.deleteById(id);
    }catch (EmptyResultDataAccessException e){
        throw new ResourceNotFoundException(id);
    }catch(DataIntegrityViolationException e) {
        throw new DatabaseException(e.getMessage());
    }

}

// public metodo update(){}

}

Classe ProdutoForm

public class ProdutoForm {
    private String nome;
    private String descricao;
    private Double preco;
    private String imgUrl;

    public ProdutoForm() {

    }

    public ProdutoForm(String nome, String descricao, Double preco, String imgUrl) {
        this.nome = nome;
        this.descricao = descricao;
        this.preco = preco;
        this.imgUrl = imgUrl;
    }

    public ProdutoForm(Produto produto) {

        this.nome = produto.getNome();
        this.descricao = produto.getDescricao();
        this.preco = produto.getPreco();
        this.imgUrl= produto.getImgUrl();
    }


    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Double getPreco() {
        return preco;
    }

    public void setPreco(Double preco) {
        this.preco = preco;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public Produto converter() {
        return new Produto (null,nome,descricao, preco, imgUrl);
    }

public Produto atualiza (Long id, ProdutoRepository produtoRepository) {

        Produto produto = produtoRepository.getById(id);
        produto.setNome(this.nome);
        produto.setDescricao(this.descricao);
        produto.setPreco(this.preco);
        produto.setImgUrl(imgUrl);

        return produto;
    }

Classe ProdutoResource - seria o Controller


@RestController
@RequestMapping(value = "/produtos")
public class ProdutoResource {

    @Autowired
    private ProdutoService serv;
    @Autowired
    private ProdutoRepository rep;

    @GetMapping
    @Transactional
    public ResponseEntity<List<ProdutoDto>> findAll() {
        List<Produto> produtos = serv.findAll();
        List<ProdutoDto> dto = ProdutoDto.convert(produtos);
        return ResponseEntity.ok().body(dto);
    }

    @GetMapping(value = "/{id}")
    @Transactional
    public ResponseEntity<ProdutoDto> findById(@PathVariable Long id) {
        ProdutoDto obj = serv.findById(id);
        return ResponseEntity.ok().body(obj);
    }

    @PostMapping
    @Transactional
    public ResponseEntity<ProdutoForm> inserir(@RequestBody ProdutoForm form) {
        Produto produto = form.converter();
        serv.inserir(produto);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(produto.getId())
                .toUri();

        return ResponseEntity.created(uri).body(new ProdutoForm(produto));
    }

    @DeleteMapping(value = "/{id}")
    @Transactional
    public ResponseEntity<Void> delete(@PathVariable Long id) {

        serv.delete(id);
        return ResponseEntity.noContent().build();
    }

    @PutMapping(value = "/{id}")
    @Transactional
    public ResponseEntity<ProdutoDto> update(@PathVariable Long id, @RequestBody ProdutoForm form) {

        Optional<Produto> prod = rep.findById(id);

        if (prod.isPresent()) {
            Produto produto = form.atualiza(id, rep);
            return ResponseEntity.ok(new ProdutoDto(produto));
        }
        return ResponseEntity.notFound().build();

    }
}
solução!

Oi Gabriel,

Ao utilizar service você pode colocar as lógicas nela mesmo, lidando inclusive com os dtos:

@RestController
@RequestMapping(value = "/produtos")
public class ProdutoResource {

    @Autowired
    private ProdutoService service;

    @GetMapping
    @Transactional
    public ResponseEntity<List<ProdutoDto>> findAll() {
        return ResponseEntity.ok().body(service.buscarTodos());
    }

    @GetMapping(value = "/{id}")
    @Transactional
    public ResponseEntity<DetalhesProdutoDto> findById(@PathVariable Long id) {
        return ResponseEntity.ok(service.buscarPorId(id));
    }

    @PostMapping
    @Transactional
    public ResponseEntity<DetalhesProdutoDto> inserir(@RequestBody ProdutoForm form, UriComponentsBuilder uriBuilder) {
        DetalhesProdutoDto dto = service.inserir(form);
        URI uri = uriBuilder.path("/{id}").buildAndExpand(dto.getId()).toUri();

        return ResponseEntity.created(uri).body(dto);
    }

    @PutMapping(value = "/{id}")
    @Transactional
    public ResponseEntity<DetalhesProdutoDto> update(@PathVariable Long id, @RequestBody ProdutoForm form) {
        DetalhesProdutoDto dto = service.atualizar(id, form);
        return ResponseEntity.ok(dto);
    }

    @DeleteMapping(value = "/{id}")
    @Transactional
    public ResponseEntity delete(@PathVariable Long id) {
        service.deletar(id);
        return ResponseEntity.noContent().build();
    }

}
@Service
public class ProdutoService {

    @Autowired
    private ProdutoRepository repository;

    public List<ProdutoDto> buscarTodos() {
        return repository.findAll().map(ProdutoDto::new).collect(Collectors.toList());
    }

    public DetalhesProdutoDto buscarPorId(Long id) {
        return new DetalhesProdutoDto(repository.findById(id).get());
    }

    public DetalhesProdutoDto inserir(ProdutoForm form) {
        Produto produto = new Produto(form.getNome(), form.getDescricao(), form.getPreco(), form.getImgUrl());
        return new DetalhesProdutoDto(repository.save(produto));
    }

    public DetalhesProdutoDto atualizar(Long id, ProdutoForm form) {
        Produto produto = repository.findById(id).get();
        produto.atualizarDados(form.getNome(), form.getDescricao(), form.getPreco(), form.getImgUrl());

        return new DetalhesProdutoDto(produto);
    }

    public void deletar(Long id) {
        repository.deleteById(id);
    }

}

Funcionou Professor, senhor é demais

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software