简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM