JodaTime有JPA,PostgreSQL和NULL值 [英] JodaTime with JPA, PostgreSQL and NULL values

查看:188
本文介绍了JodaTime有JPA,PostgreSQL和NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将带有JPA的JodaTime DateTime字段保存到PostgreSQL,但是遇到了指向数据库NULL值的空指针的麻烦。

I'm trying to persists JodaTime DateTime fields with JPA to PostgreSQL but run into troubles with null pointers to database NULL values.

我正在使用NetBeans 7 beta 2 IDE。持久性实现是EclipseLink 2.2.0,我使用EclipseLink Converter来使映射工作。以下是我的字段声明:

I'm working with the NetBeans 7 beta 2 IDE. The persistence implementation is EclipseLink 2.2.0 and I'm using an EclipseLink Converter to get the mapping to work. Here is the declaration of my field:

@Converter(
    name="dateTimeConverter",
    converterClass=ejb.util.DateTimeConverter.class
)
@Column(columnDefinition="TIMESTAMP WITH TIME ZONE")
@Convert("dateTimeConverter")
private DateTime testdate;

转换器类:

public class DateTimeConverter implements Converter {

    private Logger log;
    private static final long serialVersionUID = 1L;

    @Override
    public Object convertObjectValueToDataValue(Object o, Session sn) {
        if (o == null) {
            log.info("convertObjectValueToDataValue returning null");
            return null;
        }
        return ((DateTime)o).toDate();
    }

    @Override
    public Object convertDataValueToObjectValue(Object o, Session sn) {
        if (o == null) {
            log.info("convertDataValueToObjectValue returning null");
            return null;
        }
        return new DateTime(o);
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public void initialize(DatabaseMapping dm, Session sn) {
        log = Logger.getLogger("ejb.util.DateTimeConverter");
    }

}

只要有是一个实际的DateTime集。但是一旦没有设置,EclipseLink似乎就会假设一个字符串类型,并且postgresql开始抱怨类型字符的值变化。我假设这是因为转换器类返回空指针而不是日期对象,而EclipseLink则返回默认值。

This works fine as long as there is an actual DateTime set. But as soon as it is not set EclipseLink seems to assume a string type and postgresql starts complaining about the value being of the type character varying. I assume this is because the converter class is returning a null pointer instead of a date object and EclipseLink falls back on a default.

有没有办法让它无法切换到普通的java.util.Date?

Is there a way to get this to work short of switching to plain java.util.Date?

推荐答案

当使用 @Converter 时,EclipseLink不知道类型,因此您需要初始化它。

When a @Converter is used, EclipseLink does not know the type, so you need to initialize it.

在你的初始化(DatabaseMapping dm,Session sn)方法中,你需要设置类型,

In your initialize(DatabaseMapping dm, Session sn) method you need to set the type,

dm.setFieldClassification(java.sql.Date.class);
// or, dm.setFieldClassification(java.sql.Timestamp.class);

这篇关于JodaTime有JPA,PostgreSQL和NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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