Search code examples
javaspringhibernatespring-data-jpahibernate-mapping

Created by , Updated by column cannot be null spring jpa error


I am using spring boot and jpa and i want to save data in table. I have database table constraint not null on createdBy, updatedBy, updationDate, creatingDate columns.

I have similar DTO to entity and above mentioned audit fields are not in DTO but only in entity so meaning user don't send audit information.

On entity i am using this @EntityListeners(AuditingEntityListener.class).

Problem is when i try to update entity by rep.save(entity) i get this error "Column 'CreatedBy' cannot be null

My entity is using auditing entity listeners and it looks similar to this

    @Column(name = "isactive")
    private boolean active;
    @CreatedBy
    @Column(name = "createdby")
    private String createdBy;
    @CreatedDate
    @Column(name = "creationdate")
    private Instant creationDate;
    @LastModifiedBy
    @Column(name = "lastupdateby")
    private String lastUpdateBy;
    @LastModifiedDate
    @Column(name = "lastupdatedate")
    private Instant lastUpdateDate;

Note: If i try to create new object, it gets saved and worked fine and also audit information in database like created by updated by is also populated using auditing entity listener. But when it try to update the same object i get the error of createdBy cannot be null, i am assuming these audit fields createdBy updatedBy .... should also be populated of filled by auditEntityListener the same way i create it by post request.


Solution

  • you can use the updatable = false flag, e.g.

    @Column(name = "createdby", updatable = false)
    

    and

    @Column(name = "creationdate", updatable = false)
    

    that helped me to solve this issue.