JPA(EclipseLink),类型处理没有重复的@Converter批注? [英] JPA (EclipseLink), type handling without repeated @Converter annotations?

查看:84
本文介绍了JPA(EclipseLink),类型处理没有重复的@Converter批注?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将一个类设置为通过EclipseLink以特定方式序列化,而不必每次使用时都对其进行标记?例如,假设我有一个班级:

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

    ...
}

我希望将其作为字符串 a = 1,b = 2存储在数据库的一列中。我不希望将其序列化为Blob,而是真正将其最终作为字符串存储在VARCHAR列中。我可以使用转换器来做到这一点,但随后在使用该类的任何地方都需要添加注释:

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;

    ...

}

上面的方法不起作用,因为它不知道如何转换没有注释的类型-我希望能够有效地为该类型注册一个默认转换器。 (我尝试使用Serializable / Externalizable没有成功,因为我最终尝试将字节数组插入数据库。)

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.)

标准的JPA或EclipseLink? Hibernate似乎有@TypeDef之类的东西,听起来好像可以完成这项工作,但是我正在使用EclipseLink。

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.

推荐答案

使用转换器是最好的方法。您可以定义一个SessionCustomizer来扫描您的项目并设置转换,也可以创建自己的自定义ConversionManager,但是在映射上显式设置转换器是最好的方法。

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.

这篇关于JPA(EclipseLink),类型处理没有重复的@Converter批注?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆