Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map Duration type with JPA

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 is telling me it is an invalid type, which doesn't shock me.

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.

like image 478
HDave Avatar asked Jan 23 '23 02:01

HDave


1 Answers

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

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));
    }
}
like image 131
Pascal Thivent Avatar answered Jan 29 '23 16:01

Pascal Thivent