问题描述
我们正在处理一个非常旧的数据库,其日期在数据库中以 YYYYMMDD 的形式存储在数据库中,例如,今天(2014年7月16日)存储为 20140716 。
我们目前正在通过实现我们自己的 AttributeConverter& ; Date,Long> ,它将 Date 对象转换为 Long ,反之亦然。 p>
但是,数据库中还有一个限制,该列不允许 NULL 值。该列本身是可选的,但如果日期不存在,日期应该保持为零( 0 ),而不是 NULL $因此,我们在 AttributeConverter 中所做的事情如下所示:
$ code $> b
$ b
@Override
public Long convertToDatabaseColumn(输入日期){
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);
}
退出;
}
但是在调试时我们注意到当日期 null ,所以它永远不会转换为零。
有没有办法强制Hibernate(4.3.5。最后)使用我们的转换器,即使值 null ?
正如您已经确定的,这似乎是一个BUG报告。
典型的解决方法(在JPA 2.1中完美的工作)是将该列映射到一个简单的(即没有 AttributeConverter) Long 字段/属性并隐藏它(使其变为私有)并公开另一个类型为 Date 的字段来转换它。
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?
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.
这篇关于JPA / Hibernate映射为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!