首页 > 解决方案 > 在 Hibernate 中为 LocalDateTime 创建列类型 Datetime

问题描述

使用 JPA 在 MariaDB 中创建列类型 Datetime 的正确方法是什么?我试过这个:

@Column
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime created_at;

但我得到例外:

Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property: org.plugin.entity.Transactions.created_at

你能提出一些解决方案吗?

标签: javahibernatejpa

解决方案


spring-boot-starter-data-jpa具有hibernate-core作为编译依赖项的依赖项。

如果您使用的是 spring boot 1.4.x 或更高版本,您将获得 Hibernate 5:

https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa/1.4.0.RELEASE

您只需添加以下依赖项:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
    <version>5.0.0.Final</version>
</dependency>

它提供对 Java 8 LocalDateTime API 的支持。

如果您使用 Spring Boot 版本 2.xx 或更高版本spring-boot-starter-data-jpa,则带有内置 Java 8 LocalDateTime API 的 hibernate 5.2,因此不需要额外的依赖项。

你可以简单地写:

private LocalDateTime created_at;

推荐阅读