Fil
Fil

Reputation: 2016

Setting database-agnostic default column timestamp using Hibernate

I'm working on a java project full of Hibernate (3.3.1) mapping files that have the following sort of declaration for most domain objects.

<property name="dateCreated" generated="insert">
     <column name="date_created" default="getdate()" />
</property>

The problem here is that getdate() is an MSSQL specific function, and when I'm using something like H2 to test subsections of the project, H2 screams that

getdate() 

isn't a recognized function. It's own timestamping function is

current_timestamp(). 

I'd like to be able to keep working with H2 for testing, and wanted to know whether there was a way of telling Hibernate "use this database's own mechanism for retrieving the current timestamp". With H2, I've come up with the following solution.

CREATE ALIAS getdate AS $$ java.util.Date now() { return new java.util.Date(); } $$;
CALL getdate();

It works, but is obviously H2 specific.

I've tried extending H2Dialect and registering the function getdate(), but that doesn't seem to be invoked when Hibernate is creating tables. Is it possible to abstract the idea of a default timestamp away from the specific database engine?

Upvotes: 1

Views: 4728

Answers (2)

Pascal Thivent
Pascal Thivent

Reputation: 570615

Could you try the following (without generated since your database is not generating the value):

<column  name="DATE_CREATED" sql-type="timestamp"  default="CURRENT_TIMESTAMP"/>

Upvotes: 2

matt b
matt b

Reputation: 140061

Have you tried using a <timestamp> mapping inside your <class>?

The docs aren't very clear but it sounds like this should result in mapping a column whose value is a timestamp.

You can specify if Hibernate should use a database generated value by setting either generated="insert" or generated="always".

Upvotes: 1

Related Questions