Witam,
Pytanie jak w temacie. Jak powinno się to zrobić prawidłowo? Co prawda to co napisałem działa i zapisuje dane do bazy, ale przy walidacji dostaję informację o błędzie.
[Field error in object 'showing' on field 'movie': rejected value [2]; codes [typeMismatch.showing.movie,typeMismatch.movie,typeMismatch.com.app.models.Movie,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [showing.movie,movie]; arguments []; default message [movie]]; default message [Failed to convert property value of type [java.lang.String] to required type [com.app.models.Movie] for property 'movie'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.OneToOne com.app.models.Movie] for value '2'; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Provided id of the wrong type for class com.app.models.Movie. Expected: class java.lang.Long, got class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class com.app.models.Movie. Expected: class java.lang.Long, got class java.lang.String]]
@RequestMapping(value = {"/add"}, method = RequestMethod.POST)
public ModelAndView processAddCinemaForm(@Valid @ModelAttribute("showing") Showing showing, BindingResult result, HttpServletRequest request) {
Long idOfMovie = Long.parseLong(result.getFieldValue("movie").toString());
showing.setMovie(movieService.findOne(idOfMovie));
if(result.hasErrors()){
System.out.println(result.getAllErrors());
}
if (showing.getId() != null) {
System.out.println(showing.getMovie());
Showing newShowing = showingService.findOne(showing.getId());
newShowing = showing;
showingService.save(showing);
} else {
showingService.save(showing);
}
return new ModelAndView("redirect:/showing/all");
}
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout">
<div layout:fragment="content">
<form action="#" th:action="@{/showing/add}" th:object="${showing}" method="post">
<br/><input type="hidden" th:field="*{id}" class="form-control" placeholder="Id"/>
<select th:field="*{movie}" class="dropdown">
<option th:each="movie : ${movies}"
th:value="${movie.id}"
th:text="${movie.title}">Wireframe
</option>
</select>
<br/>
<button type="submit" class="btn btn-md btn-primary pull-right">Save</button>
</form>
</div>
</html>