我遇到了一个非常沮丧的问题。。我无法使用JPA保存函数来存储SQL的正确日期时间对象,我得到了以下错误:
com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
这是我的代码:
控制器内:
import java.sql.Timestamp;
@PostMapping("/record")
public String updateRecord(@RequestParam("createDatetime") Timestamp createDatetime) {
Date date = new Date();
Timestamp ts=new Timestamp(date.getTime());
Record record = new Record();
Record.setCreateDatetime(ts);
recordService.save(record);
}
实体内:
private Timestamp createDatetime;
@Column(name = "createDatetime")
public Timestamp getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Timestamp createDatetime) {
this.createDatetime= createDatetime;
}
非常感谢!!
我建议您使用现代java.time
的LocalDateTime
。JPA自动将LocalDateTime
转换为数据库datetime
。要获取当前日期时间,请使用LocalDateTime.now()
。
private LocalDateTime createDatetime;
@Column(name = "createDatetime")
public LocalDateTime getCreateDatetime() {
return createDatetime;
}
您也可以将作为@RequestParam
@PostMapping("/record")
public String updateRecord(@RequestParam("createDatetime") LocalDateTime createDatetime) {
...
}
尝试用@TemporalType.TIMESTAMP注释createDateTime字段。