JPA (EclipseLink), type handling without repeated @Converter annotations?

时光毁灭记忆、已成空白 提交于 2019-12-11 06:36:36

问题


Is it possible to set a class to be serialised in a particular way by EclipseLink, without tagging it as such every time it is used? For example, say I had a class:

class MyObj {
    private int a;
    private int b;

    public MyObj(int a, int b) {
        this.a = a;
        this.b = b;
    }

    ...
}

I want this to be stored in a column in the database as a string "a=1,b=2". I don't want it to be serialised to a blob, but to genuinely end up as a string in a VARCHAR column. I can do this with a converter, but I then need to have an annotation everywhere I use the class:

@Entity
class User {
    @Column(name="first")
    private MyObj one;

    @Column(name="second")
    private MyObj two;

    ...

}

The above won't work, as it doesn't know how to convert the type without annotations - I want to be able to effectively register a default converter for the type. (I've tried playing with Serializable/Externalizable without success, as I end up trying to insert an array of bytes into the database.)

Is this possible, either with standard JPA or EclipseLink? Hibernate seems to have something like @TypeDef which sounds like it might do the job, but I'm using EclipseLink.


回答1:


Using a Converter is the best way. You could define a SessionCustomizer that scans your project and sets the convert, or create your own custom ConversionManager, but explicitly setting the converter on the mapping is the best way.




回答2:


There doesn't appear to be a way of doing this, which seems a shame. In the end I annotated the class members with the conversion to use explicitly.




回答3:


You can make the get an setter-method with standard-types and convert it yourself. For example:

@Entity class User { @Column(name="first") private MyObj one;

public void setOne(String myObj){
     one = convert(myObj);
}

public String getOne(){
    return convertBack(one);
}

}



来源:https://stackoverflow.com/questions/4961655/jpa-eclipselink-type-handling-without-repeated-converter-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!