Spring Boot 学习笔记 7 : ZonedDateTime 和 Hibernate

最近项目的实体类中使用了 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。

tinyblob

测试类:

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);
    }

}

测试类输出结果:

out

为了修改数据库字段类型为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;

exception

在网上搜索后知道可能是由于和 spring-data-jpa 中 hibernate-core 依赖版本冲突引起的异常,查看 maven 依赖:

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 。

datetime

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值