springit icon indicating copy to clipboard operation
springit copied to clipboard

Link conversion error upon submission of a new comment

Open deligkarisk opened this issue 5 years ago • 0 comments

This issue relates to lecture 76, adding a new comment.

When executing the "Post" operation, upon submission of a new comment, the Link field (as part of the Comment Object) cannot be converted to an actual Link and therefore comes back null (thus with Binding errors).

The error shown upon debugging is something like "org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'comment' on field 'link': rejected value [com.kosmas.springit.domain.Link@49c33fdc];....no matching editors or conversion strategy found)

My solution was to

  1. Define a Link converter class from String to Link
  2. Override the ToString method in Link to return simply a string of the id.

In combination, the two changes result in the Link object being converted appropriately. Not sure if this is the best way to solve this, so happy to hear any alternative solutions.

This is the code for the Link Converter class.

package com.kosmas.springit.converter;

import com.kosmas.springit.domain.Link;
import com.kosmas.springit.repository.LinkRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class LinkByIdConverter implements Converter<String, Link> {

    private LinkRepository linkRepository;

    @Autowired
    public LinkByIdConverter(LinkRepository linkRepository) {
        this.linkRepository = linkRepository;
    }

    @Override
    public Link convert(String id) {
        return linkRepository.getOne(Long.parseLong(id));
    }

}

deligkarisk avatar Aug 20 '20 00:08 deligkarisk