Spring boot使用jpa自动添加当前时间

2019-06-14  本文已影响0人  寻找大海的鱼

一.application.properties配置文件

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2b8
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

二.实体类

在实体类上面添加@Entity和@EntityListeners(AuditingEntityListener.class)注解,
在createDate和updateDate字段上分别添加@CreatedDate和@LastModifiedDate注解

@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String phone;

    private String password;

    @CreatedDate
    private Date createDate;

    @LastModifiedDate
    private Date updateDate;
}

三.启动类

在springboot启动类上面添加@EnableJpaAuditing注解

@SpringBootApplication
@EnableJpaAuditing
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(QbtApplication.class, args);
    }
}
上一篇下一篇

猜你喜欢

热点阅读