简体   繁体   English

Spring JPAF无法将值“为什么?”从类型[java.lang.String]转换为类型[java.lang.Long]。

[英]Spring JPAFailed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Why?'

I'm not understanding why when I attempt to use a modelAttributed form in with spring it's attempting to convert my String type variable to a Long type variable when it should just remain a String type. 我不明白为什么当我尝试在spring中使用modelAttributed形式时,它试图将我的String类型变量转换为Long类型变量,而它应该只是String类型。 Only thing I suspect it's trying to do is fill the Id variable. 我怀疑它唯一想做的就是填充Id变量。

Failed to convert value of type 'java.lang.String' to required type'javaSpring.DojoOverflow.models.Questions'; 无法将类型“ java.lang.String”的值转换为所需类型“ javaSpring.DojoOverflow.models.Questions”; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Why?'; 嵌套的异常是org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型[java.lang.Long]的值“为什么?”; nested exception is java.lang.NumberFormatException: For input string: "Why?" 嵌套的异常是java.lang.NumberFormatException:对于输入字符串:“为什么?”

//---------------------------------------------------
// My Model
@Entity
@Table(name="questions")
public class Questions {
    // Attributes
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotEmpty(message = "Ask a question!")
    private String question;
    @Column(updatable=false)
    private Date createdAt;
    private Date updatedAt;
    @OneToMany(mappedBy="question", fetch = FetchType.LAZY)
    private List<Answer> answers;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable (
       name="questions_tags",
       joinColumns = @JoinColumn(name="question_id"),
       inverseJoinColumns = @JoinColumn(name="tag_id")  
    )
    @Size (max=3)
    @NotEmpty(message="Tag your question!")
    private List<Tag> tags;

// ------------------------------------- 
// My Controller Mapping
@PostMapping("/questions/new")
public String processQuestion(@Valid @ModelAttribute("question")Questions   question, BindingResult result) {
    if(result.hasErrors()) {
        return "newQuestion.jsp";
    }
    questionService.createQuestion(question);
    return "redirect:/";
}

//-----------------------------------------------
// My jsp
<body>
<div class="container">
<h1>What is your question?</h1>
<form:form action="/questions/new" method="post" modelAttribute="question">
    <div class="form-group">        
        <form:label path="question">Question</form:label>
        <form:textarea rows="5" class="question form-control" path="question"/>
        <span class="error"><form:errors path="question"/></span>
    </div>
    <div class="form-group">        
        <form:label path="tags">Tags</form:label>
        <form:input class="tags form-control" placeholder="Tags"   path="tags"/>
        <span class="error"><form:errors path="tags"/></span>
    </div>
    <button class="btn btn-secondary" type="submit">Submit</button>
</form:form>
<a href="/questions">Go Back</a>
</div>
</body> 

Looks like an incompletely initialized object. 看起来像一个未完全初始化的对象。 Check your createQuestion service method, and be sure each required field for Question is set before you pass it to the controller. 检查您的createQuestion服务方法,并在将问题传递给控制器之前 ,确保已设置“问题”的每个必填字段。 That form alone doesn't have all the necessary fields. 仅该表格没有所有必填字段。

I suggest to apply MVVC pattern to separate your business object from your view object. 我建议应用MVVC模式将业务对象与视图对象分开。

You expect to receive only strings from the view in your model attribute object. 您希望仅从模型属性对象的视图中接收字符串。

Your entity object contains a list of tags and a list of answers => they are modeled differently and the usage of the same class is difficult, with many potential bugs. 您的实体对象包含一个标签列表和一个答案列表=>它们的建模方式不同,并且使用同一类很困难,并且存在许多潜在的错误。

In your case it is better to create.a separate view class only with strings and convert them to your entity object. 在您的情况下,最好只使用字符串创建一个单独的视图类,并将它们转换为您的实体对象。

Example : 范例:

public class QuestionModelAttribute {
       private String tags;
       private String answers;
       .....
 }

and your method will receive: 您的方法将收到:

@PostMapping("/questions/new")
public String processQuestion(@Valid @ModelAttribute("question") QuestionModelAttribute questionModelAttribute, BindingResult result) {
   Questions question = questionsService.convertQuestion(questionModelAttribute);
   questionService.save(question);
   ..
}

Your view will receive in the model a QuestionModelAttribute 您的视图将在模型中收到QuestionModelAttribute

<form:form action="/questions/new" method="post" modelAttribute="questionModelAttribute">

This pattern offers a healthy decoupling between the view and model. 这种模式在视图和模型之间提供了健康的解耦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在 SPRING 中将类型“java.lang.String”的值转换为所需的类型“java.lang.Long” - Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long' in SPRING Spring NumberFormatException:无法将类型&#39;java.lang.String&#39;的值转换为所需的类型&#39;java.lang.Long - Spring NumberFormatException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long 无法将 Spring JPA 从类型 [java.lang.String] 转换为类型 [java.lang.Long]? - Failed to convert from type [java.lang.String] to type [java.lang.Long] for Spring JPA? &quot;message&quot;: &quot;无法从类型 [java.lang.String] 转换为类型 [java.lang.Long] 以获取值 &#39;count&#39;;对于输入字符串:\\&quot;count\\&quot;&quot; - "message": "Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'count'; For input string: \"count\"" 提交表单时,无法将“java.lang.String”类型的值转换为所需类型“java.lang.Long”错误 - Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long' error when submitting form 如何解决错误:无法将类型&#39;java.lang.String&#39;的值转换为所需的类型&#39;java.lang.Long&#39;; - How do I fix error: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; 无法将类型“java.lang.String”的值转换为所需类型“java.lang.Long”嵌套异常 java.lang.NumberFormatException 对于输入字符串“null” - Failed convert value of type 'java.lang.String' to required type 'java.lang.Long' nested excep java.lang.NumberFormatException For input string “null” 当Get请求不是ID时,获取此异常:无法将类型java.lang.String的值转换为所需的类型java.lang.Long - when the Get request is other than Id getting this exception :Failed to convert value of type java.lang.String to required type java.lang.Long spring 无法将“java.lang.String”类型的值转换为所需的“java.lang.reflect.Type”类型 - spring failed to convert value of type 'java.lang.String' to required type 'java.lang.reflect.Type' java.lang.IllegalArgumentException:找到了多个参数类型候选:[java.lang.String]和[java.lang.Long] - java.lang.IllegalArgumentException: Found more than one parameter type candidate: [java.lang.String] and [java.lang.Long]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM