mysql注解spring boot @@ Json Format中如何只保存分秒小时

how to save only the minute and second hour in mysql annotation springboot @@ JsonFormat

我正在使用 springboot 和 spring-data 创建一个 crud,用户将其保存在变量“entry”中,我希望它只有小时:分钟:秒,我尝试使用 @JsonFormat (pattern = "HH: mm: ss" ) 但错误

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "19:47:11": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '19:47:11' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 19:47:11 of type java.time.format.Parsed; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "19:47:11": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '19:47:11' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 19:47:11 of type java.time.format.Parsedat [Source: (PushbackInputStream); line: 10, column: 20] (through reference chain: br.com.lucas.entity.Acao["entrada"])]

我怎样才能只节省一个小时?

我们可以通过添加带有模式参数的 JsonFormat 注释来更改响应 class 的格式。标准 SimpleDateFormat 规则适用。

@JsonFormat(pattern = "HH:mm:ss")
private LocalTime localTime;

我在一个简单的例子上试过了,我想和你分享。如果你尝试这个没有报错,但是你在你的模型中试的时候报错,你需要检查数据库中的相关列是否为time,如果不是,请尝试。

我们来创建一个模型作为示例。

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalTime;

@Entity
public class Time {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @JsonFormat(pattern = "HH:mm:ss")
    private LocalTime localTime;

    public Time() {
    }

    // getter/setter ..
}

现在让我们创建一个存储库。

import org.springframework.data.jpa.repository.JpaRepository;

public interface TimeRepository extends JpaRepository<Time, Long> {}

现在让我们创建一个控制器。

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TimeController {

    private final TimeRepository timeRepository;

    public TimeController(TimeRepository timeRepository) {
        this.timeRepository = timeRepository;
    }

    @PostMapping(value = {"/time"})
    public Time time(@RequestBody Time time) {
        timeRepository.save(time);
        return time;
    }
}

现在让我们向 /time 路径发送一个 Json 请求。

{
    "localTime": "02:30:00"
}

你会得到这样的结果。

{
    "id": 1,
    "localTime": "02:30:00"
}

我建议您阅读 this article,在那里您可以找到更全面的解决方案。