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?
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With