views:

144

answers:

1

I need LastUpdatedDttm to be updated by SYSDATE whenever record is updated. But below annoataions do nt work as desired. SYSDATE is inserted only once and not updated for subsequent updations. Also, lastUpdDTTM is not part of sql generated by hibernate.

@Generated(GenerationTime.ALWAYS)
@Column(name="LAST_UPDATED_DTTM",insertable=false,updatable=true, columnDefinition ="timestamp default SYSDATE")
private Date lastUpdDTTM;

@Generated(GenerationTime.ALWAYS)
@Column(name="CREATED_DTTM", insertable=false, updatable=false)
private Date createdDTTM;
A: 

(...) SYSDATE is inserted only once and not updated for subsequent updates.

First of all, let me make something clear: Generated means that the field is generated by the database and that Hibernate needs to read it after insert/update to update the entity. Using default SYSDATE in the column definition works fine for an INSERT but for an UPDATE, you'll need a trigger.

Also, lastUpdDTTM is not part of sql generated by hibernate.

Well, you told Hibernate that the field is ALWAYS generated by the database so I'm not surpised that Hibernate doesn't include it in the generated SQL (actually, I believe that this somehow conflicts with udpatable = true, I would expect Hibernate to complain about it).

Anyway, as I said, it's not Hibernate that will update this field, it's the database and you need a trigger, Hibernate will just refresh the entity after an update to get the new value.


A different approach would be to use callback annotations, for example for the last update date:

@PreUpdate
protected void updateDates() {
    lastUpdDTTM = new Date();
}

For better consistency, you could even use the same approach for the creation date with @PrePersit:

@PrePersist
@PreUpdate
protected void updateDates() {
    Date now = new Date();
    if (createdDTTM == null) {
        createdDTTM = new Date(now.getTime());
    }
    lastUpdDTTM = now;
}
Pascal Thivent
Thanks again. But I really dont want to use triggers. Is there no otehr solution to it?
jpanewbie
I wish I could use callbacks. It has to DB server datetime. This approach will give me webserver current time.
jpanewbie
@jpanewbie Indeed. Last idea then: use a `default SYSDATE` for the update date too and set the update date to `null` in a `@PreUpdate` method.
Pascal Thivent
LastUpDttm col is NOT NULL default Sysdate at the DB level. @Generated(GenerationTime.ALWAYS) @Column(name="LAST_UPDATED_DTTM", insertable=false, updatable=false, columnDefinition = "timestamp default SYSDATE") private Date lastUpdDTTM;Even If I set the field null in @Preupdate method it is ignored.
jpanewbie