views:

153

answers:

1

I have MySql table that has a date field with zeroes ("0000-00-00") as its default value (field cannot be null, I can't change table structure). Hibernate doesn't like zero dates and throws exception during read or save.

I managed to make it read records by setting MySql connection setting "zeroDateTimeBehavior=convertToNull" that converts zero dates to nulls while retrieving records. It is all working fine until I try to save the record that has null date - it throws exception that date cannot be null.

So the question is - how to save record through Hibernate so date will appear as zeroes in a table?

Thanks.

+1  A: 

I'd try to add an Hibernate Interceptor (API, Doc) and try to implement something in the onSave() method.

The following code may work:

static final Date ZERO_DATE = //0000-00-00

public boolean onSave(Object entity,
               Serializable id,
               Object[] state,
               String[] propertyNames,
               Type[] types)
        throws CallbackException {
 for(int i = 0; i< propertyNames.length; i++) {
  if(propertyNames[i].equals("dateFieldName") && state[i]==null) {
   state[i] = ZERO_DATE;
   return; //or may continue, if there are several such fields.
  }
 }
}
David Rabinowitz
But what exactly is ZERO_DATE?
serg
The java represntation of a date field with just zeroes.
David Rabinowitz
Can you give an example how it looks? There is no such thing in java as date with all zeroes, that's why there is a problem with zero dates.
serg
There is no such thing *anywhere* as a date with all zeroes. That thing in MySQL is not a date value.
Lasse V. Karlsen