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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With