Skip to content
Advertisement

How to use JPA to save datetime of SQL to fix: “Conversion failed when converting date and/or time from character string.”

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

Advertisement

Answer

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) {
    ...
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement