Reputation: 725
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?
Upvotes: 6
Views: 4953
Reputation: 24895
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.
Upvotes: 4
Reputation: 10301
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
Upvotes: 5
Reputation: 1138
Integer type, length as required. Either use a static unit (i.e. milliseconds) or store the unit in a separate field - if you're using JPA2, it has enum to string mapping for this.
If you're using JPA 2.1, you can probably even use a @Converter
, eliminating the need for conversion code in your entities.
Upvotes: 1