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. Only thing I suspect it's trying to do is fill the Id variable.
Failed to convert value of type 'java.lang.String' to required type'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?'; nested exception is java.lang.NumberFormatException: For input string: "Why?"
//---------------------------------------------------
// 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>