简体   繁体   中英

Hibernate - record date attribute first got data

I want to record the date that a attribute in a entity first got data.

For example:

@Entity
public class Sales(){

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String salesNote;

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date salesNoteCreationDate;
}

I tried to do this in the Service layer by comparing:

    if (!saleView.getsalesNote().isEmpty() && saleDb.getPlan().getNotes().isEmpty()) {
        Date salesNoteCreationDate = new Date();
        saleView.setsalesNoteCreationDate(salesNoteCreationDate);
    }

This only half worked, because the salesNoteCreationDate isn't sent to the UI, if the above test fails and the date is not set the null value in saleView overwrites the saleDb value which may hold a valid date.

I suspect there is a simpler way either through using @Version or a Hibernate Listener - having looked at the Hibernate docs I am none the wiser on this particular issue.

Why don't you just put this logic where it belongs: encapsulated in the entity, rather than in the UI?

@Entity
public class Sale {

    private String note;

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date noteCreationDate;

    public void setNote(String note) {
        if (this.note == null && note != null) {
            this.noteCreationDate = new Date();
        }
        this.note = note;
    }
}

Note that I renamed your entity to Sale (since an instance of that class probably represents one sale, and not multiple ones). Also note that I removed the sales prefix on your fields, which are fields of the Sale class,making this prefix redundant.

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