Thursday, February 18, 2010

Hibernate and dates

I've come back to a Hibernate problem that I had in my last role which revolves around how java.util.Dates are handled. The problem is this: you populate your POJO with java.util.Dates and persist it. Magically, these objects are turned into java.sql.Timestamps.

Sun warns you about this in a rather odd statement in the Java API.

"[I]t is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance."

Therefore:

aDate.equals(aTimestamp)


does not mean

aTimestamp.equals(aDate)


So, what? Gavin King says:

"Note that no self-respecting code should EVER call equals on a Timestamp."

But when you start putting objects into java.util.Collections, you no longer directly control if or when an equals method is called on your objects.

This lead me to post a bug report (and proposed fix) since what I saw in our project was that upon each transaction, either our POJO had all its Dates or non at all, alternating with each call. Clearly not good! The call was supposed to be idempotent.

Sadly, there has been no interest in my bug report. And although my fix works (albeit somewhat inefficiently), it would be nice to see Hibernate keep java.util.Dates as java.util.Dates.

No comments:

Post a Comment