操作数据库映射实体类时,通常需要记录createTime和updateTime,如果每个对象新增或修改去都去手工操作创建时间、更新时间,会显得比较繁琐。
Springboot jpa提供了自动填充这两个字段的功能,简单配置一下即可。@CreatedDate、@LastModifiedDate、@CreatedBy、@LastModifiedBy前两个注解就是起这个作用的,后两个是设置修改人和创建人的,这里先不讨论。
首先,我们的很多实体类都是需要创建时间和更新时间的,我们不想在每个实体类里都去定义这两个字段,那么我们把它抽取到基类中,让实体类去继承它。
package com.tianyalei.testautotime.entity;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
/**
* Created by wuwf on 17/4/21.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.