Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with zero dates ("0000-00-00") in Hibernate?

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.

like image 698
serg Avatar asked Nov 14 '22 15:11

serg


1 Answers

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.
        }
    }
}
like image 65
David Rabinowitz Avatar answered Dec 25 '22 02:12

David Rabinowitz