Spring Data JPA 的时间注解:@CreatedDate 和 @LastModifiedDate

版权声明:欢迎关注我的个人公众号:超级码里奥。如果这对您有帮助,欢迎点赞和分享,转载请注明出处 https://blog.csdn.net/qq_28804275/article/details/84801457

选择 Spring Data JPA 框架开发时,常用在实体和字段上的注解有@Entity@Id@Column等。在表设计规范中,通常建议保留的有两个字段,一个是更新时间,一个是创建时间。Spring Data JPA 提供了相应的时间注解,只需要两步配置,就可以帮助开发者快速实现这方面的功能。

  1. 在实体类上加上注解 @EntityListeners(AuditingEntityListener.class),在相应的字段上添加对应的时间注解 @LastModifiedDate@CreatedDate

注意:日期类型可以用 Date 也可以是 Long

@Entity
@EntityListeners(AuditingEntityListener.class)
public class User {

     /**
     * 自增主键
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

     /**
     * 更新时间
     */
    @LastModifiedDate
    @Column(nullable = false)
    private Long updateTime;

     /**
     * 创建时间
     */
    @CreatedDate
    @Column(updatable = false, nullable = false)
    private Date createTime;

    // 省略getter和setter
  1. 在Application启动类中添加注解 @EnableJpaAuditing
@EnableJpaAuditing
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
    
}

此外,Spring Data JPA 还提供 @CreatedBy@LastModifiedBy 注解,用于保存和更新当前操作用户的信息(如id、name)。如果有这方面的需求,可以参考下面的配置实现:

@Entity
@EntityListeners(AuditingEntityListener.class)
public class User {

     /**
     * 自增主键
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

     /**
     * 更新时间
     */
    @LastModifiedDate
    @Column(nullable = false)
    private Long updateTime;

     /**
     * 创建时间
     */
    @CreatedDate
    @Column(updatable = false, nullable = false)
    private Date createTime;
    
     /**
     * 创建人
     */
    @CreatedBy
    private Integer createBy;

    /**
     * 最后修改人
     */
    @LastModifiedBy
    private Integer lastModifiedBy;

    // 省略getter和setter

配置实现AuditorAware接口,以获取字段需要插入的信息:

@Configuration
public class AuditorConfig implements AuditorAware<Integer> {

    /**
     * 返回操作员标志信息
     *
     * @return
     */
    @Override
    public Optional<Integer> getCurrentAuditor() {
        // 这里应根据实际业务情况获取具体信息
        return Optional.of(new Random().nextInt(1000));
    }

}

欢迎关注我的个人公众号:超级码里奥
如果这对您有帮助,欢迎点赞和分享,转载请注明出处

猜你喜欢

转载自blog.csdn.net/qq_28804275/article/details/84801457
今日推荐