Witam,
Mam encję, w której jest kolumna:
@Column(name = "birth_date", nullable = false)
private LocalDate birthDate;
Na stronie html mam formularz, który posiada pole:
<input th:field="*{birthDate}" data-toggle="datepicker" class="form-control"
name="birthDate"
id="birthDate"
placeholder="Data urodzenia" type="text" required>
DatePicker ma ustawiony format: yyyy/MM/dd.
Po zatwierdzeniu formularza chcę zobaczyć czy kontroler prawidłowo odczytał wszystkie pola.
@PostMapping
public String register(@Valid @ModelAttribute("client") Client client, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
for (int i = 0; i < bindingResult.getAllErrors().size(); i++) {
System.out.println(bindingResult.getAllErrors().get(i).getObjectName());
System.out.println(bindingResult.getAllErrors().get(i).getCode());
System.out.println(bindingResult.getAllErrors().get(i).toString());
}
}
System.out.println(client);
// userService.createAccount(client);
return BANK;
}
Pole daty jest puste.
Błąd jaki występuje:
Field error in object 'client' on field 'birthDate': rejected value [2018/01/10]; codes [typeMismatch.client.birthDate,typeMismatch.birthDate,typeMismatch.java.time.LocalDate,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [client.birthDate,birthDate]; arguments []; default message [birthDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'birthDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalDate] for value '2018/01/10'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018/01/10]]
Próbowałem - https://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/ ale nie działa.
Ustawianie formatu w @InitBinder też nie działa.
java.sql.Date również wywala ten sam błąd.
Zmiana LocalDate na java.util.Date działa ale tego nie chcę.
Zmiana w setterze działa ale tak się raczej robić nie powinno:
public void setBirthDate(String birthDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
this.birthDate = LocalDate.parse(birthDate, formatter);
}
Edit: problem rozwiązany.
1. Dodanie zależności w Mavenie:
```xml
<dependency>
<groupid>org.hibernate</groupid>
<artifactid>hibernate-java8</artifactid>
<version>5.0.1.Final</version>
</dependency>
```
2. Dodanie adnotacji do pola w encji:
```java
@DateTimeFormat(pattern = "yyyy/MM/dd")
```