LocalDate形式

cro*_*ked 6 java mysql spring hibernate thymeleaf

我有一个关于Spring + Thymeleaf日期格式的问题.我有一个简单的实体与LocalDate date字段.我希望从表单中的用户获取此日期并将其保存到MySQL数据库.我收到这样的错误:

无法将类型为java.lang.String的属性值转换为属性日期所需的类型java.time.LocalDate; 嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型java.lang.String转换为类型java.time.LocalDate,值为2019-04-30; 嵌套异常是java.time.format.DateTimeParseException:无法在索引2处解析文本2019-04-30

我的实体:

@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields
Run Code Online (Sandbox Code Playgroud)

Thymeleaf观点/形式:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">    
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>
Run Code Online (Sandbox Code Playgroud)

这个问题的原因是什么?也许还有其他更好的存储日期方式?

cro*_*ked 8

问题解决了..我不知道为什么,但改变我的模板:

<input type="date" th:value="*{date}" th:field="*{date}" />
Run Code Online (Sandbox Code Playgroud)

并添加@DateTimeFormat(pattern = "yyyy-MM-dd")到实体字段解决了问题.

  • 是的,添加@DateTimeFormat是这里的关键部分. (2认同)