Ad

[Failed To Convert Property Value Of Type 'java.lang.String' To Required Type 'java.sql.Time'

- 1 answer

I have a error when I try to send a form to my controller, I have this error:

[Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Time' 'horaire' on field 'heureDebut': rejected value [10:00]; codes [typeMismatch.horaire.heureDebut,typeMismatch.heureDebut,typeMismatch.java.sql.Time,typeMismatch]

This is my Entity:

@Entity(name = "horaire")
public class Horaire {

    @Id @GeneratedValue
    @Column(name = "idhoraire")
    private Integer id;
    @Column(name = "heure_debut")
    private Time heureDebut;
    @Column(name = "heure_fin")
    private Time heureFin;


    public Horaire() {
    }

    public Integer getId() {
        return id;
    }

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

    public Time getHeureDebut() {
        return heureDebut;
    }

    public void setHeureDebut(Time heureDebut) {
        this.heureDebut = heureDebut;
    }

    public Time getHeureFin() {
        return heureFin;
    }

    public void setHeureFin(Time heureFin) {
        this.heureFin = heureFin;
    }

    @Override
    public String toString() {
        return "Horaire{" +
                "id=" + id +
                ", heureDebut=" + heureDebut +
                ", heureFin=" + heureFin +
                '}';
    }
}

This is my method in the controller:

@GetMapping("/save")
public String saveHoraire(@Valid Horaire horaire) {

    horaireRepository.save(horaire);

    return "redirect:listeHoraire";

}

this is my template:

<form th:action="@{save}" method="get"  th:object="${horaire}">
    <input type="text"  th:field="*{id}">
    <input type="time"  th:field="*{heureDebut}">
    <input type="time"  th:field="*{heureFin}">
    <input type="submit" value="valider"/>
</form>
Ad

Answer

Use java.util.Date in your entity class like shown below and datetime in the database.

@Column(name = "heure_debut")
@Temporal(TemporalType.TIMESTAMP)
private Date heureDebut;

@Column(name = "heure_fin")
@Temporal(TemporalType.TIMESTAMP)
private Date heureFin;

and use the SimpleDateFormat to convert string to Date object

String text = "25/02/1992";
Date date = new SimpleDateFormat("DD/MM/YYYY").parse(text);
Ad
source: stackoverflow.com
Ad