JPA (EclipseLink), type handling without repeated

2019-08-14 01:16发布

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.

3条回答
对你真心纯属浪费
2楼-- · 2019-08-14 01:22

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.

查看更多
Evening l夕情丶
3楼-- · 2019-08-14 01:28

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);
}

}

查看更多
Luminary・发光体
4楼-- · 2019-08-14 01:43

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.

查看更多
登录 后发表回答