如何在Hibernate中使用零日期(" 0000-00-00")? [英] How to work with zero dates ("0000-00-00") in Hibernate?

查看:97
本文介绍了如何在Hibernate中使用零日期(" 0000-00-00")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySql表有一个带有零(0000-00-00)的日期字段作为其默认值(字段不能为空,我不能更改表结构)。 Hibernate不喜欢零日期并在读取或保存期间抛出异常。

通过设置MySql连接设置zeroDateTimeBehavior = convertToNull,可以将零日期转换为空值,同时检索记录,从而设法读取记录。这一切都工作正常,直到我试图保存具有空日期的记录 - 它抛出异常,日期不能为空。

所以问题是 - 如何保存记录通过Hibernate所以日期会在表中显示为零?

谢谢。

解决方案

拦截器( API Doc ),并尝试在onSave()方法中实现一些东西。



以下代码可能有效:

  static final Date ZERO_DATE = // 

$ public boolean onSave(Object entity,
Serializable id,
Object [] state,
String [] propertyNames,$ b $ (类型[]类型)
throws CallbackException {
for(int i = 0; i< propertyNames.length; i ++){
if(propertyNames [i] .equals(dateFieldName) && state [i] == null){
state [i] = ZERO_DATE;
return; //或者可以继续,如果有几个这样的字段。
}
}
}


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.

解决方案

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.
        }
    }
}

这篇关于如何在Hibernate中使用零日期(&quot; 0000-00-00&quot;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆