简体   繁体   English

将参数传递给 jpa 转换器

[英]pass parameter to jpa converter

I am trying to write a generic Converter to be used in multiple similar cases in my code.我正在尝试编写一个通用Converter ,用于我的代码中的多个类似情况。 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我有一组子类,我只想使用一个Converter来处理,所以我想将一些东西(类类型/一些参数/等)传递给Converter以便能够定义

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?这是否可行?

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我看到的唯一方法是使GenericConverter抽象,定义一个带有您要修改的参数的构造函数

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的子类。

@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.我没有看到其他好的选择,因为AttributeConverter接口不会向您传递已转换的Field ( AnnotatedElement )。 Thus you can't create an own annotation and lookup this one.因此,您无法创建自己的注释并查找此注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM