springmvc整合spring-data-jpa使用审计注解@CreatedDate、@LastModifiedDate问题

2,355 阅读2分钟

springmvc整合spring-data-jpa使用审计注解@CreatedDate、@LastModifiedDate问题使用错误的问题

想要的答案是

Column 'create_time' cannot be null让jpa自动帮我们生成创建时间更新时间

第一步:实体类的写法

  • @Column

  • @GeneratedValue(strategy= GenerationType.IDENTITY)

  • @Id

  • @MappedSuperclass.( 根据情况添加该注解用在父类上面。当这个类肯定是父类时,加此标注。如果改成@Entity,则继承后,多个类继承,只会生成一个表,而不是多个继承,生成多个表.

  • @EntityListeners(AuditListener.class).( 实体监听对实体属性变化的跟踪,它提供了保 存前,保存后,更新前,更新后,删除前,删除后等状态,就像是拦截器一样,你可以在拦截方法里重写你 的个性化逻辑。

  • @CreationTimestamp 使用该注解可以让Hibernate在插入时针对注解的属性对应的日期类型创建默认值。

  • @UpdateTimestamp 使用该注解可以让Hibernate在更新时时针对注解的属性对应的日期类型创建默认值。


/**
 * @program: BaseEntity
 * @description: 基础实体公共属性
 * @author: hewo
 * @create: 2020-12-20 20:42
 **/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Column(name="id",nullable=false,length=11)
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Id
    private Long id;//唯一id

    @Column(name="create_time",nullable=false)
    @CreationTimestamp
    @CreatedDate
    private Date createTime;//创建时间

    @Column(name="update_time",nullable=false)
    @UpdateTimestamp
    @LastModifiedDate
    private Date updateTime;//更新时间
    
    // getter和setter省略。。。。

/**
 * @program: OperaterLog
 * @description: 日志的实体类
 * @author: hewo
 * @create: 2020-12-20 20:12
 **/
@Entity
@Table(name = "zc_operater_log")
@EntityListeners(AuditingEntityListener.class)
public class OperaterLog extends BaseEntity {

    @Column(name = "operater",nullable = false,length = 11)
    private String operater;

    @Column(name = "content",nullable = false,length = 128)
    private String content;

    public String getOperater() {
        return operater;
    }

    public void setOperater(String operater) {
        this.operater = operater;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

第二步添加spring-aspects.jar依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
</dependency>

第三步在配置文件中springmvc-config.xml添加jpa审计

<!--jpa审计-->
<jpa:auditing />

😀😀😀😀😀😀😀😀 这个是我遇到的问题,自己记录下。