java - 表单中的 LocalDate

标签 java mysql spring hibernate thymeleaf

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

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

我的实体:

@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

Thymeleaf View /表单:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">    
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>

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

最佳答案

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

<input type="date" th:value="*{date}" th:field="*{date}" />

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

关于java - 表单中的 LocalDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079923/

相关文章:

mysql - 如何使用Java根据最后5分钟的时间戳检索mysql数据

java - Spring Controller 中的 Autowiring bean注入(inject)

java - 在mavenLocal()中为.jar文件成功添加gradle依赖关系之后,我如何实际从Java类导入和使用该jar

java - Activiti BPMN 引擎 : store custom property in Database

python - 编辑 MySQLdb Python 中使用的 C 编译器

java - 如何构建JPA实体和JSON模型?

java - PreparedStatement.addBatch() 可以用于 SELECT 查询吗?

java - 桌面应用程序层

mysql - 使用 AES_ENCRYPT 在 Eloquent 模型中加密

java - Sencha Cmd 5 + Java 8 错误