How to simulate java.time.duration in a Mysql database

I am writing a simple application to learn Java EE, and I need to store an object in my MySQL DB that contains java.time.duration .

What is the best way to store it?

+5
source share
3 answers

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

However, you have several methods ( toString and parse ) that provide you with a path by converting to String; vg

 @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 receivers for myDurationString .

Optionally, you can use toMillis() and ofMillis() if you prefer a number in milliseconds.

+4
source

Since 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

+4
source

Whole type, length as needed. Either use a static unit (i.e., Milliseconds), or save the device in a separate field - if you use JPA2, there is an enumeration for matching strings for this.

If you are using JPA 2.1, perhaps you can even use @Converter , eliminating the need for code conversion in your entities.

+1
source

Source: https://habr.com/ru/post/1213032/


All Articles