Date Mapping between Java and Hibernate.

This is small piece of information that I came across while I was viewing some forum on hibernate and Java mapping. Worth remembering!

Managing dates as lookup objects (keys) in Java is tricky. The java.sql.Date has a granularity of 1 day, but it’s based on java.util.Date, which has a granularity of 1 millisecond. Oracle Dates have a granularity of 1 second. I can personally attest to the grief that this can cause, both with JDO and with OpenJPA. So the date you write may not be the date you read.

In fact, this such a nuisance that I opened an issue on the OpenJPA documentation, requesting that the documentation devote a section to explaining this problem and how to avoid it.

“Operation attempted on a deleted instance” refers to OpenJPA’s understanding of the data, not what’s actually in the database. If a delete has been scheduled but not yet committed to the database, for example, you’d get that message.

While you might not think you’d deleted the record, problems with data granularity might be to blame. An date in memory could have been written out the the database, purged from local memory, then the date read back in from the database truncated (in Oracle’s case, to seconds). This might cause it to look like another date, possibly also truncated. In other words, something like a hash collision. The first object might have been explicitly deleted, but since both objects had the same date, deleting the second object would appear to be an attempt to delete the first object for a second time.

Tim Holloway

Advertisements

About this entry