pass parameter to jpa converter

Viewed 909

I am trying to write a generic Converter to be used in multiple similar cases in my code. I have a set of subclasses that I want to handle using only one Converter, so I want to pass something (class type / some parameter / etc) to the Converter to be able to define

public class GenericConverter implements AttributeConverter<MyGenericClass , Integer> {
.
.
.
    public MyGenericClass convertToEntityAttribute(Integer arg0) {
                // return a certain sub class here according to an attribute / an initialization method / etc
            }

and in the entities:

@Convert( converter = GenericConverter.class \*pass something here\* )
    protected SubClass1 var1;

@Convert( converter = GenericConverter.class \*pass something here\* )
    protected SubClass2 var2;

@Convert( converter = GenericConverter.class, \*pass something here\* )
    protected SubClass3 var3;

Is this doable by any means?

1 Answers

I want to pass something (class type / some parameter / etc) to the Converter to be able to define

The only way I see is to make the GenericConverter abstract, define a constructor with the parameters you would like to modify

public abstract GenericConverter {

   protected GenericConverter(Class<?> type, String someParameter, Object etc){
       ....
   }
}

create subclasses and pass that arguments.

public class SubClass1Converter extends GenericConverter {

    public SubClass1Converter(){
        super(SubClass1.class, "someValue", ....);
    }
}

Then you can use the subclasses in the @Convert.

@Convert(converter = SubClass1Converter.class)

I don't see other good options since the AttributeConverter interface does not pass you the Field (AnnotatedElement) that is converted. Thus you can't create an own annotation and lookup this one.

Related