Search code examples
javadatabasehibernateormhibernate-mapping

Saving a property of an Hibernate entity with the value from a database function


I have an Hibernate entity which has a java.util.Date property. Instead of setting the property value to new Date() on my entity and then saving with Hibernate, I would like to make the database set the date through a SYSDATE() function. I want this because I can't rely on the date set by the client, because it is a swing app. I can only trust on the time taken from the database.

I have thought of some options, but both seem quite poor:

  • Ask the database for the current time, set it on my object and then save. (expensive)
  • Create an Hibernate insert statement and pass the parameters manually. (subverts the purpose of Hibernate)

Solution

  • Hibernate allows you to have DB generated columns, check the Generated properties Hibernate documentation.

    You database should have a DEFAULT SYSDATE configuration.

    Check this example for a complete solution.