Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Parameterized instances of AttributeConverter

We are developing an application connected to a legacy database. This is very "untyped", using strings for almost all data. What is worse is that is far of being homogeneous: it uses different patterns for dates or times ('YYDDMM', 'HHMMSS', milliseconds) and booleans ('Y'/'N', 'X'/' '), for example.

We want to use JPA (EclipseLink) and custom converters. The problem is that @Convert expects a class implementing AttributeConverter, so we have to do new classes for each pattern. What I'd like is a BooleanConverter class, which can be instantiated with values 'Y'/'N' or 'X'/' '.

This is obviously out of JPA spec, but maybe it's possible using EclipseLink annotations/configuration. Looking at its @Convert annotation, a converter can be specified by name. This sounds good to me if I can register a ynBooleanConverter and xSpaceBooleanConverter:

// Unfortunately, this method does not exist :(
Session.addConverter('ynBooleanConverter', new BooleanConverter("Y", "N")); 

@Entity
public class MyEntity {

    @Convert("ynBooleanConverter")
    private Boolean myBoolean;

    ...
}

Is it possible? What other options do we have?

like image 977
sinuhepop Avatar asked Oct 07 '15 16:10

sinuhepop


1 Answers

Try @ObjectTypeConverter:

@Entity
@ObjectTypeConverters({
    @ObjectTypeConverter(name = "ynBooleanConverter", objectType = Boolean.class, dataType = String.class, 
        conversionValues = { 
        @ConversionValue(objectValue = "true", dataValue = "Y"), 
        @ConversionValue(objectValue = "false", dataValue = "N") }),
    @ObjectTypeConverter(name = "xSpaceBooleanConverter", objectType = Boolean.class, dataType = String.class, 
        conversionValues = { 
        @ConversionValue(objectValue = "true", dataValue = "X"), 
        @ConversionValue(objectValue = "false", dataValue = " ") }),
})
public class MyEntity {

    @Convert("ynBooleanConverter")
    private boolean ynBoolean;

    @Convert("xSpaceBooleanConverter")
    private boolean xSpaceBoolean;
}
like image 156
Ish Avatar answered Sep 21 '22 06:09

Ish