如何使用 JPA 映射 Duration 类型 [英] How to map Duration type with JPA

查看:31
本文介绍了如何使用 JPA 映射 Duration 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 javax.xml.datatype.Duration 类型的类中有一个属性字段.它基本上代表一个时间跨度(例如 4 小时 34 分钟).

I have a property field in a class that is of type javax.xml.datatype.Duration. It basically represents a time span (e.g. 4 hours and 34 minutes).

JPA 告诉我这是一个无效类型,这并不让我震惊.

JPA is telling me it is an invalid type, which doesn't shock me.

这是什么好的解决方案?我可以实现我自己的 Duration 类,但我不知道如何让 JPA接受"它作为数据类型.

Whats a good solution this? I could implement my own Duration class, but I don't know how to get JPA to "accept" it as a datatype.

推荐答案

这是什么好的解决方案?我可以实现我自己的 Duration 类,但我不知道如何让 JPA接受"它作为数据类型.

Whats a good solution this? I could implement my own Duration class, but I don't know how to get JPA to "accept" it as a datatype.

JPA 不支持自定义类型,因此如果您想采用这种方式,则必须使用提供商提供的 JPA 扩展.例如,Hibernate 允许定义 您使用声明的自定义值类型@Type.显然,这会损害提供者之间的可移植性,这可能是一个问题.如果没有,那么您就知道这是可行的.

JPA does not support custom types so if you want to go this way you'll have to use a JPA extension from your provider. For example, Hibernate allows to define custom value types that you declare with @Type. Obviously, this will harm portability between providers which might be a concern. If not, then you know it is doable.

使用标准 JPA,传统方法是添加另一个 getter/setter 对,以适应有问题的属性并在访问时执行转换.我会使用 Long 来存储持续时间:

With standard JPA, the traditional approach would be to add another getter/setter pair which adapt the problematic property and perform conversion when accessed. I would use a Long to store a duration:

public MyEntity implements Serializable {
    private Long id;
    private javax.xml.datatype.Duration duration;

    @Id
    @GeneratedValue
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Transient
    public Duration getDuration() {
        return this.duration;
    }
    public void setDuration(Duration duration) {
        this.duration = duration;
    }

    public Long getDurationAsJpaCompatibleType() {
        return MyXmlUtil.convertDurationToLong(this.duration);
    }
    public void setDurationAsJpaCompatibleType(Long duration) {
        setDuration(MyXmlUtil.convertLongToDuration(duration));
    }
}

这篇关于如何使用 JPA 映射 Duration 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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