[无法将类型'java.lang.String'的属性值转换为必需类型'java.sql.Time'

时间:2018-05-03 11:02:19

标签: java spring thymeleaf

当我尝试将表单发送到控制器时出错,我有这个错误:

  

[无法将'java.lang.String'类型的属性值转换为   字段'heureDebut'上的必需类型'java.sql.Time''horaire':   被拒绝的价值[10:00];代码   [typeMismatch.horaire.heureDebut,typeMismatch.heureDebut,typeMismatch.java.sql.Time,typeMismatch]

这是我的实体:

@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 +
                '}';
    }
}

这是我在控制器中的方法:

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

    horaireRepository.save(horaire);

    return "redirect:listeHoraire";

}

这是我的模板:

<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>

1 个答案:

答案 0 :(得分:0)

在您的实体类中使用java.util.Date,如下所示,并在数据库中使用 datetime

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

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

并使用SimpleDateFormat将字符串转换为Date对象

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