如何将Joda Date持久保存到sql数据库?

成员之声

如何将jodatime YearMonth对象持久保存到sql数据库?

@Entity
public class MyEntity {
    private YearMonth date; //how to persist?
    //some more properties
}

我希望以后能够在特定月份选择所有实体。

塞巴斯蒂安

为此,您需要一个javax.persistence.Converter(请参阅如何将java.util.Date转换为Java8 java.time.YearMonth):

@Entity
public class MyEntity {
    @Convert(converter = YearMonthConverter.class)
    private YearMonth date; //how to persist?
    //some more properties
}

以下是Java8 java.time.YearMonth到java.utilDate的示例转换器。您需要将java.time.YearMonth更改为org.joda.time.YearMonth,并使用适当的方法将其转换为所需的类型/从所需的类型进行转换:(省略导入):

@Converter(autoApply = true)
public class YearMonthConverter implements AttributeConverter<YearMonth, Date> {

  @Override
  public Date convertToDatabaseColumn(YearMonth attribute) {
    // uses default zone since in the end only dates are needed
    return attribute == null ? null : Date.from(attribute.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
  }

  @Override
  public YearMonth convertToEntityAttribute(Date dbData) {
    // TODO: check if Date -> YearMonth can't be done in a better way
    if (dbData == null) return null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dbData);
    return YearMonth.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章