Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime with JPA, PostgreSQL and NULL values

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

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;

The converter class:

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");
    }

}

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.

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

like image 950
Eelke Avatar asked Mar 06 '11 10:03

Eelke


2 Answers

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

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);
like image 69
James Avatar answered Oct 12 '22 02:10

James


This article: http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/ gave me some pretty useful info on persisting the localdate to the db and it had some important differences from your DateTimeConverter implementation (specifically implementing AttributeConverter not just converter and the annotation of 'Converter' is at the class level

like image 24
janoulle Avatar answered Oct 12 '22 04:10

janoulle