Spring data Jpa自动更新实体创建时间和修改时间

梦想的初衷 提交于 2019-11-27 05:13:56

实体类中

import lombok.Data;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Date;

@Data
@Table(name = "sys_service")
@Entity
@EntityListeners(AuditingEntityListener.class)
public class SysService extends ImprovedNamingStrategy {
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Id
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "url")
    private String url;
    @Column(name = "path")
    private String path;
    @Column(name = "sort")
    private Integer sort;
    @CreatedDate
    @Column(name = "createTime",updatable = false,nullable = false)
    private Date createTime;
    @LastModifiedDate
    @Column(name = "updateTime",nullable = false)
    private Date updateTime;
}

启动类中添加注解

@EnableJpaAuditing

在插入对象时,不需要传入createTime和updateTime的值,@CreatedDate和@LastModifiedDate自动获取当前时间,再次修改时 createTime属性设置 updatable=false,值不再改变。

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!