添加JPA注释时出现Spring ConversionFailedException

时间:2016-11-04 15:20:06

标签: java spring hibernate spring-mvc jpa

我正在学习Spring,而且我正在学习这些教程。我有一个表单提交示例,并尝试使用Hibernate / JPA存储结果。该示例适用于以下实体:

package hello;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
//import javax.persistence.Id;

//@Entity
public class Comment {

//  @Id
//  @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @NotNull
    @Size(min=2, max=150)
    private String comment;

    @Size(min=2, max=150)
    private String name;

    @Override
    public String toString() {
        return String.format("Comment[id=%d, comment='%s', name='%s']", id, comment, name);
    }

    public long getId() {
        return id;
    }

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

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

但是,如果我删除JPA注释行,则示例在验证表单时会抛出以下异常:

2016-11-04 14:59:32.716  WARN 17749 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [hello.Comment]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Comment'; nested exception is java.lang.NumberFormatException: For input string: "Comment field..."

这似乎表明它正在尝试将为实体的“评论”字段提交的值转换为Long。是否提供注释以指定该字段是字符串?我原以为它会检查java类型。或者我做错了什么? 如果您需要剩下的代码,请告诉我。

编辑:删除此存储库后错误停止:

package hello;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface CommentRepository extends CrudRepository<Comment, Long> {

    List<Comment> findByName(String name);
}

“评论,长期”部分有什么问题吗?我从示例中复制了这些并查看了CrudRepository的API,它看起来是正确的,因为实体类型是Comment,ID类型是Long。

我正在使用以下方法绑定WebMvcConfigurerAdapter中的值:

@PostMapping("/")
public String checkPersonInfo(@Valid Comment comment, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "form";
    }

    return "redirect:/results";
}

0 个答案:

没有答案