英文:
How to use JPA to save datetime of SQL to fix: "Conversion failed when converting date and/or time from character string."
问题
我遇到了一个非常令人沮丧的问题...我无法使用JPA的保存函数来存储SQL的正确日期时间对象,我遇到了以下错误:
com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
这是我的代码:
在Controller中:
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);
}
在Entity中:
private Timestamp createDatetime;
@Column(name = "createDatetime")
public Timestamp getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Timestamp createDatetime) {
this.createDatetime = createDatetime;
}
非常感谢!
英文:
I got a very frustrated problem.. I cannot use the JPA save function to store correct datetime object of SQL, I got the following error:
com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
There is my code:
In Controller:
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);
}
In Entity:
private Timestamp createDatetime;
@Column(name = "createDatetime")
public Timestamp getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Timestamp createDatetime) {
this.createDatetime= createDatetime;
}
Many thanks!!
答案1
得分: 1
我建议您使用现代的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) {
// ...
}
英文:
I recomend you to use LocalDateTime
of modern java.time
. JPA automatically convert LocalDateTime
into database datetime
. To get current datetime use LocalDateTime.now()
.
private LocalDateTime createDatetime;
@Column(name = "createDatetime")
public LocalDateTime getCreateDatetime() {
return createDatetime;
}
You can take as @RequestParam
also
@PostMapping("/record")
public String updateRecord(@RequestParam("createDatetime") LocalDateTime createDatetime) {
...
}
答案2
得分: 0
尝试使用 @Temporal(TemporalType.TIMESTAMP) 注释 createDateTime 字段。
英文:
Try to annotate createDateTime field with @Temporal(TemporalType.TIMESTAMP).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论