Coder Guru
Coder Guru

Reputation: 513

Spring boot JPA @Entity create temporary variable

I am using JPA in spring boot to save information to DB. I have audit information like creationDate and updationDate and I am saving it to DB, saving the data like creationDate and updationDate in the @PrePersist and @PreUpdate methods. I want this update conditonal so I added boolean flag boolean auditInformationFlag but it considers auditInformationFlag variable as database column. is it possible to have transient attribute in this class

@Entity
@Table(name = "TestDB")
public class TestEntity implements Serializable {
        @Column(name = "creationdate",nullable = false,  insertable = true, updatable = false)
    private Timestamp creationDate;

    @Column(name = "updationdate",nullable = false,  insertable = true, updatable = true)
    private Timestamp modificationDate;

    private boolean auditInformationFlag;


    public boolean isAuditInformationFlag() {
        return auditInformationFlag;
    }

    public void setAuditInformationFlag(boolean auditInformationFlag) {
        this.auditInformationFlag = auditInformationFlag;
    }

    public Timestamp getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Timestamp creationDate) {
        this.creationDate = creationDate;
    }


    public Timestamp getModificationDate() {
        return modificationDate;
    }

    public void setModificationDate(Timestamp modificationDate) {
        this.modificationDate = modificationDate;
    }

    @PrePersist
    protected void onCreate() {
        if(auditInformationFlag){
            this.setCreationDate(new Timestamp((new Date()).getTime()));
            this.setModificationDate(new Timestamp((new Date()).getTime()));            
        }
    }

    @PreUpdate
    protected void onUpdate() {
        if(auditInformationFlag){
            this.setModificationDate(new Timestamp((new Date()).getTime()));            
        }
    }
 }

Upvotes: 2

Views: 5326

Answers (1)

Alien
Alien

Reputation: 15878

but it considers auditInformationFlag variable as database column

Because you need to annotate the field with Transient.@Transient annotation is used to indicate that a field is not to be persisted in the database.

you can create transient variable in entity class like below by putting @Transient annotation on top of field.

@Transient
private boolean auditInformationFlag ;

Upvotes: 3

Related Questions