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.

Answer

I got the solution, When we need to update the entity that is using AuditEntityListener i updated only the changed fields in entity comparing to DTO. MapStruct made it easy

void updateEntity(@MappingTarget Entity target, DTO dto); now save the updated entity.

Leave a Reply

Your email address will not be published. Required fields are marked *