Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to model java.time.duration in Mysql Database

I am writing a simple application to get to know Java EE, and I need to save an entity into my MySQL DB, which contains a java.time.duration.

What is the best way to store that?

like image 714
olkoza Avatar asked Feb 10 '15 08:02

olkoza


2 Answers

As Hibernate 4.3 supports JPA 2.1 you can use the AttributeConverter class:

@Converter
public class DurationToStringConverter implements AttributeConverter<Duration, String>
{

    @Override
    public String convertToDatabaseColumn(Duration duration)
    {
        return duration == null ? null : duration.toString();
    }

    @Override
    public Duration convertToEntityAttribute(String dbData)
    {
        return dbData == null ? null : Duration.parse(dbData);
    }
}

@Entity
public class Ent {

    @Column
    @Convert(DurationToStringConverter.class)
    Duration duration;

}

See: http://docs.oracle.com/javaee/7/api/javax/persistence/Convert.html

like image 103
flo Avatar answered Sep 18 '22 01:09

flo


Unfortunately, JPA still does not support the types of the new java.time package

That said, you have a couple of methods (toString and parse) that provide you a way by converting to String; v.g.

@Transient
private Duration myDuration;

@Column(name="DURATION")
String myDurationString;

@PostLoad
public void init() {
  this.myDuration = this.myDurationString == null ? null : Duration.parse(this.myDurationString);
};

public Duration getMyDuration() {
  return this.myDuration;
}

public void setMyDuration(Duration _myDuration) {
  this.myDurationString = _myDuration == null ? null : _myDuration.toString();
}

Remember that you should not include getters and getters for myDurationString.

Optionally, you could use toMillis() and ofMillis(), if you are more comfortable with the number as milliseconds.

like image 43
SJuan76 Avatar answered Sep 19 '22 01:09

SJuan76