Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Link conversion error upon submission of a new comment #3

Open
deligkarisk opened this issue Aug 20, 2020 · 0 comments
Open

Link conversion error upon submission of a new comment #3

deligkarisk opened this issue Aug 20, 2020 · 0 comments

Comments

@deligkarisk
Copy link

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));
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant