springboot Entity数据库pojo中Date字段,默认使用系统时间怎么设置注解?

1. springboot Entity数据库pojo中Date字段,默认使用系统时间怎么设置注解?

可以使用注解@CreateDateTIme和@LastModifiedDate来设置Date字段的默认值为系统时间。

例如:

@Entity
public class User {
   @Id
   private Long id;
   
   private String name;
   
   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
   @CreatedDate // 使用该注解表示该字段是创建时间,自动填充当前时间
   private Date createTime; 
   
   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
   @LastModifiedDate // 使用该注解表示该字段是更新时间,自动更新当前时间
   private Date updateTime; 

   // 省略Getter和Setter方法
}

需要在启动类加入@EnableJpaAuditing注解才能生效。例如:

@SpringBootApplication
@EnableJpaAuditing
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注