最近项目的实体类中使用了 Java8 中新的日期和时间 API,在数据持久化时遇见一些曲折,记录下来作为前车之鉴。
Task 实体类:
import com.*.*.domain.enumration.TaskStatus;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.time.ZonedDateTime;
/**
* 任务实体类
*
* @author smileorsilence
* @date 2018/04/28
*/
@ToString
@Entity
@Table(name = "task")
public class Task implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(name = "uuid", unique = true)
private String uuid;
@Column(name = "priority")
private Integer priority = 10;
@Column(name = "created_time")
// @Temporal(TemporalType.TIMESTAMP)
// org.hibernate.AnnotationException:
// @Temporal should only be set on a java.util.Date or java.util.Calendar property
private ZonedDateTime createdTime;
// 省略getters & setters & equals & hashCode ...
}
修改前的 maven 依赖:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
此时 Task 实体类字段 createdTime 映射到数据库的数据类型是 tinyblob 类型,且长度为0。
测试类:
package com.*.*.service.impl;
import com.*.*.domain.Task;
import com.*.*.domain.util.Time;
import com.*.*.repository.TaskRepository;
import com.*.*.service.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
/**
* @author smileorsilence
* @date 2018/04/28
*/
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TaskServiceImplTest {
@Inject
private TaskRepository taskRepository;
@Test
public void createTask() throws Exception {
Task task = new Task();
task.setUuid(UUIDGenerator.getUUID());
task.setCreatedTime(Time.getNow());
taskRepository.saveAndFlush(task);
}
@Test
public void findAllTask() throws Exception {
taskRepository.findAll().stream().forEach(System.out::println);
}
}
测试类输出结果:
为了修改数据库字段类型为datetime,在 Task 实体类字段 createdTime 上添加注解 @Temporal 后抛出异常:
org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property.
后来知道 Hibernate 对于 Java8 中出现的新的日期和时间 API 也提供了支持,只需添加 Hibernate 对 Java8 的支持依赖:
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-java8 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.2.10.Final</version>
</dependency>
maven repository 附有一段依赖描述:
(deprecated - use hibernate-core instead) Support for Java8-specific features - mainly Java8 Date/Time (JSR 310)
说明该依赖已经过时,应使用 hibernate-core 核心包代替,于是在 pom.xml 文件中添加如下依赖:
<!--https://mvnrepository.com/artifact/org.hibernate/hibernate-core-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
这时候使用 Java8 中新的日期和时间类型,与数据库中的日期和时间类型之间的映射是隐式的,不需使用 @Temporal 注解。
运行测试后抛出异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties;
在网上搜索后知道可能是由于和 spring-data-jpa 中 hibernate-core 依赖版本冲突引起的异常,查看 maven 依赖:
排除 spring-data-jpa 中的 hibernate 依赖即可:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
</exclusions>
</dependency>
这时候 Task 实体类字段 createdTime 映射到数据库的数据类型为 datetime 。