一般来说创建时间和修改时间 两个字段是一个实体类必备的。在阿里Java开发手册中也对此的说明:
【强制】表必备三字段:id, create_time, update_time。
说明:其中 id 必为主键,类型为 bigint unsigned、单表时自增、步长为 1。create_time, update_time
的类型均为 datetime 类型,前者现在时表示主动式创建,后者过去分词表示被动式更新。
在JPA 中也是支持新的数据保存是自动写入创建时间,当数据有修改时 自动记录修改时间。在SpringBoot 的启动类上加 @EnableJpaAuditing 来开启时间的支持, 在字段上使用 @CreatedDate 和@LastModifiedDate 注解来即可完成时间的自动更新。
实例:
@EnableJpaAuditing
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
@EntityListeners(value = AuditingEntityListener.class)
@Getter
@Setter
@Entity
public class StudentEntity {
....
@CreatedDate
@Column(nullable = false, updatable = false)
private LocalDateTime createTime;
@LastModifiedDate
@Column()
private LocalDateTime updateTime;
...
}
由于这两个字段所有实体类都有,所以可以将它们抽取到一个通用的类里面,其他实体类需要时直接继承即可。
/**
* 所有类的超类
* 自动更新创建时间和更新时间
*
* @author peter
*
**/
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
@Getter
@Setter
public abstract class AbstractBaseTimeEntity {
@CreatedDate
@Column(nullable = false, updatable = false)
private LocalDateTime createTime;
@LastModifiedDate
@Column()
private LocalDateTime updateTime;
}
@Entity
@Data
public class StudentEntity extends AbstractBaseTimeEntity {
....
}