Search code examples
jpatimetypesannotationsduration

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.


Solution

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