Saturday, September 17, 2016

TIMESTAMP implementations with Hibernate JPA

Definition of the TIMESTAMP field may be done in different ways and it depends on a particular use case which method is more appropriate. The post gives several examples of TIMESTAMP implementation, but it does not pretend to explain all the options.
The examples below are the use cases, that were met and implemented during my experience in real projects.
DB schema definition in the examples is done with the MySQL dialect and may differ for other dialects.

Immutable TIMESTAMP generated by DB on record creation

Generating immutable TIMESTAMP value by DB upon record creation is a very common case. Setting of a TIMESTAMP value is fully under DB responsibility and is reached with the DB schema definition. Java implementation includes only JPA mapping and counts on generating a value by a database.

Combination of immutable and mutable TIMESTAMPs generated by DB

This case is a combination the above cases: DB is responsible to generate CREATE_TIME column value upon a record creation and update UPDATE_TIME value upon each record update. The value of the UPDATE_TIME column should be NULL in a new record ; it should be set to the current time upon a record update.
The solution again is reached with the DB schema definition and appropriate JPA mapping.

About the author

I trust only simple code and believe that code should be handsome. This is not a matter of technology, but professional approach, consolidated after years of software development. I enjoy to cause things working and feel very happy, when I manage to solve a problem.