问题描述
我的MySql表有一个带有零(0000-00-00)的日期字段作为其默认值(字段不能为空,我不能更改表结构)。 Hibernate不喜欢零日期并在读取或保存期间抛出异常。
通过设置MySql连接设置zeroDateTimeBehavior = convertToNull,可以将零日期转换为空值,同时检索记录,从而设法读取记录。这一切都工作正常,直到我试图保存具有空日期的记录 - 它抛出异常,日期不能为空。
所以问题是 - 如何保存记录通过Hibernate所以日期会在表中显示为零?谢谢。
拦截器(,),并尝试在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中使用零日期(" 0000-00-00")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!