0

I am currently working on my first java project and have jumped into using spring/hibernate.

I have created a of API's which is used to perform CRUD operations on a database. I thought it would be a good idea to write the current time an item is added to the database.

To do this this I created a new column in the database & updated the entity I am using to write to it, with a new javafield called "timestamp" & mapped it to the database column.

I then used (or tried to) the below code to have the system set the timestamp as the item is written into the db as I am doing something similar to ensure the id is set to 0 before it auto increments.

 for (Downloads tempDownload : theDownloads) {

            // display the download 
             tempDownload.setId(0);
             tempDownload.setTimestamp(System.currentTimeMillis());
             System.out.println(tempDownload);

            // save to the database
              downloadsService.saveProduct(tempDownload);
    }   

However when the item is written to the db the timestamp is written as 0. if I remove the

tempDownload.setTimestamp(System.currentTimeMillis());

then I am able to set the time via json by manually passing it in with the payload. Is there another way to go about this, or a step I could be missing?

Kind regards,

Danny

OrangeFlavour
  • 71
  • 2
  • 10

1 Answers1

1

Since you're using System#currentTimeMillis I suppose that the field you're using to write the timestamp is of type long or Long.

If you want to save a date to a field using Hibernate, I suggest you use the recommend ways of doing so.

For example if your case, you could have your timestamp field be of type Date and just annotate it using the following scheme.

@Temporal(TemporalType.TIMESTAMP)
private Date timestamp;

then you could simply do tempDownload.setTimestamp(new Date); to set it.

Alternatively you could Java 8's new Date and Time API which can be mapped easily to the database, even without the usage of the @Temporal annotation as these map automatically to their respective SQL type.

With this in mind, the mapping scheme is:

  • LocalDate to DATE
  • LocalTime and OffsetTime to TIME
  • Instant, LocalDateTime, OffsetDateTime and ZonedDateTime to TIMESTAMP

Using the correct type for date persistence is very important. Your example merely saves the milliseconds as these are returned as an epoch. This means that you'll need to perform conversion from millis to date to do your various jobs. Futhermore, if you want to have timezone related information, following this approach is prohibitive for something like that.

akortex
  • 5,067
  • 2
  • 25
  • 57
  • Hi Aris, thank you for your response. Just to confirm I was using the long type yes. :) I used your solution above this morning and it works perfectly thank you! – OrangeFlavour Aug 29 '18 at 08:25
  • Nice always happy to help. Please also go ahead upvote and make this the suggested answer. – akortex Aug 29 '18 at 08:29