【问题标题】:How to model java.time.duration in Mysql Database如何在 Mysql 数据库中建模 java.time.duration
【发布时间】:2015-04-10 05:46:25
【问题描述】:

我正在编写一个简单的应用程序来了解 Java EE,我需要将一个实体保存到我的 MySQL DB 中,其中包含一个java.time.duration

最好的存储方式是什么?

【问题讨论】:

  • 你使用 JPA 吗?哪个提供商?

标签: java mysql jakarta-ee


【解决方案1】:

由于 Hibernate 4.3 支持 JPA 2.1,您可以使用 AttributeConverter 类:

@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;

}

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

【讨论】:

    【解决方案2】:

    很遗憾,JPA still does not support the types of the new java.time package

    也就是说,您有几个方法(toStringparse)可以通过转换为字符串来为您提供方法; 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();
    }
    

    请记住,您不应该为myDurationString 包含getter 和getter。

    如果您更愿意以毫秒为单位,您可以选择使用toMillis()ofMillis()

    【讨论】:

    • 而且,如果您使用的是 JPA 2.1,您可以在 javax.persistence.AttributeConverter 中使用相同的逻辑
    • 使用 toString() 也是我的第一个猜测,但由于我的持续时间不能超过 24 小时,我将使用 BigInt 并存储纳秒。用于回答的坦克。
    • 链接到 java.net 不再有效。应更新为github.com/javaee/jpa-spec/issues/63
    【解决方案3】:

    整数类型,长度根据需要。使用静态单位(即毫秒)或将单位存储在单独的字段中 - 如果您使用的是 JPA2,它具有枚举到字符串的映射。

    如果您使用的是 JPA 2.1,您甚至可以使用 @Converter,从而无需在实体中使用转换代码。

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2020-10-01
      • 2018-04-19
      • 1970-01-01
      相关资源
      最近更新 更多