Techiio-author
Started by Peter DanielsSep 25, 2021

Open
How can I add DB Server SYSDATE at entity level in JPA entity?

1 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWES SHARE

I want to insert and update oracle SYSDATE during insert and update the record in java JPA.

But I want to make SYSDATE at entity level in JPA . How can I achieve this so that after update or insert the record the oracle SYSDATE is reflected.

1 Replies

Techiio-commentatorNeel Dey replied 7 months ago0 likes0 dislikes

The reason why the date column gets a null value when inserting, even though it is defined as default SYSDATE dbms-side, is that the default value for a column is only used if the column is not given a value in the query. That means it must not appear in the INSERT INTO sentence, even if it has been given null.

If you want to use the default SYSDATE on the DBMS side, you should configure the @Column with insertable=false in order to get the column out of your SQL INSERTs.

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "myDate", insertable=false)
private Date myDate;

Take into account that this approach will always ignore the value you provide to the property in your app when creating the entity. If you really want to be able to provide the date sometimes, maybe you should consider using a DB trigger to set the value instead of a default value.

There's an alternative to using the default SYSDATE definition of the DBMS. You could use the @PrePersist and @PreUpdate annotations to assign the current date to the property, prior to saving/update, if and only if it has not been assigned yet:

@PrePersist
protected void onCreate() {
    if (myDate == null) { myDate = new Date(); }
}

You must be Logged in to reply
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance