简体   繁体   中英

@Createdby @CreatedDate are null after entity is updated

I've implemented auditing columns in a Spring app, and it works when i create a new entity the columns are set, but when i update the entity i find the two @Createdby and @CreatedDate are set to null, how can i make these columns unchangeable after creation :

@MappedSuperclass
public abstract class Audit implements Serializable {

    @CreatedBy
    private String createdBy;

    @CreatedDate
    private Date createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private Date lastModifiedDate;
}

For me it worked:

@MappedSuperclass
public class Auditor {

    @Column(name = "created_date", updatable = false)
    @CreatedDate
    private long createdDate;

    @Column(name = "modified_date")
    @LastModifiedDate
    private long modifiedDate;

    @Column(name = "created_by", updatable = false)
    @CreatedBy
    private String createdBy;

    @Column(name = "modified_by")
    @LastModifiedBy
    private String modifiedBy;
}

And extending the Class:

@Entity
@EntityListeners(AuditingEntityListener.class)
public class Material extends Auditor {

    @Id
    @SequenceGenerator(name = "seq_material", sequenceName = "seq_material")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_material")
    private Long id;

    @Column
    @NotBlank(message = "Nome é um campo obrigatório!.", groups = validacaoProd.class)
    private String nome;

    More...
}

And I updated the records in the database :

update material set created_date = 1618418750189, modified_date = 1618418750189 

you can use @DynamicUpdate in class-level. It will consider only update columns and ignore others to put in UPDATE query.

Ref : https://www.baeldung.com/spring-data-jpa-dynamicupdate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM