0

I am working on a Spring Data JPA project, where I want to store Oracle SYSDATE in a date field of a table. I can not modify the table at all.

Right now, what I am doing is passing new Date() to that date field. Which is not correct as the Oracle server is in a different timezone.

I am not writing any query to insert the data, instead I am using JpaRepository save() method.

How can I do this?

P.S. I do not want to hard code the timezone of the database server in my code.

Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42

1 Answers1

2

There is no direct way to do this (see Setting default values for columns in JPA).

What you could do is to perform a select SYSDATE from dual and use the result to set your property.

The method to get the sysdate could be in your Spring Data Repository

@Query(value=`select SYSDATE from dual`, nativeQuery=true)
Date currentDate();

You could set the value in a @PrePersist Listener (see onSave() (for any Entity saved with Hibernate/Spring Data Repositories) ).

But I think you can't perform queries in those listeners, so the next thing would be to create a custom implementation of Spring Data's save method, so that it gets such a value and keeps it available for the Listener, before actually saving anything. Alternatively one could use a separate connection of the query.

Obviously, this all adds another database roundtrip, which is rather expensive.

An alternative would be to get the current time of the server once and use that just to determine the correct offset to use and create the timestamps locally, using that offset. This is much faster and easier but breaks when application server and database server have different daylight saving time rules.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348