1

We're working with a really old database where dates are stored as numeric values in the database as YYYYMMDD, for example, for today (July 16th 2014) it would be stored as 20140716.

We're currently solving this by implementing our own AttributeConverter<Date, Long> which converts Date objects to Long and vice versa.

However, there's also a constraint on the database that does not allow NULL values in the column. The column itself is optional, but if the date is not existing, the date should be persisted as zero (0) in stead of NULL.

So, what we did in our AttributeConverter is the following:

@Override
public Long convertToDatabaseColumn(Date input) {
    Long out = 0L;
    if (input != null) {
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTime(input);
        out += (cal.get(Calendar.YEAR) * 10000);
        out += (cal.get(Calendar.MONTH) + 1) * 100;
        out += cal.get(Calendar.DAY_OF_MONTH);
    }
    return out;
}

But while debugging we noticed that our converter is not executed when the date is null, so it's never converted to zero.

Is there a way we can still force Hibernate (4.3.5.Final) to use our converter, even if the value is null?

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
  • What version of Hibernate are you using? – JamesB Jul 16 '14 at 10:26
  • 1
    Not sure if this is related, I cannot open this link from work: https://hibernate.atlassian.net/browse/HHH-8697 – JamesB Jul 16 '14 at 10:29
  • That indeed describes our problem and applies to Hibernate 4.3.0.Beta5. The issue itself is unresolved though and no workaround is provided. – g00glen00b Jul 16 '14 at 10:31

1 Answers1

0

As you have identified, it seems to be a BUG reported here.

The typical workaround (that works perfectly in JPA<2.1) is to map that column to a simple (i.e without AttributeConverter) Long field/property and to hide it (make it private) and expose another field of type Date that converts it.

V G
  • 18,822
  • 6
  • 51
  • 89
  • We ended up using this approach indeed. Too bad we can't use the converter though. – g00glen00b Jul 16 '14 at 13:38
  • 1
    This bug has been fixed and will be in the next release. The 5.0.0.Beta1 release is on the maven central if you are willing to use beta releases. – Driss Amri Apr 11 '15 at 20:31