0

How can I persist a jodatime YearMonth object to a sql database?

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

I want later to be able to pick all entities by a specific month.

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

2

The better question is how do you intend to use the data in the database? Generally you want to store dates in databases using data types supported by the target database as opposed to strings or composite integers. That would allow you to use the built in database date/time functions and validations as opposed to needing to implement that logic in your application.

You can certainly add methods to your entity to convert to/from jodatime values to your entity for the parts of your application that need it.

user3745362
  • 229
  • 1
  • 5
1

You need a javax.persistence.Converter for this (see How to convert java.util.Date to Java8 java.time.YearMonth):

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

The following is an example converter for Java8 java.time.YearMonth to java.utilDate. You need to change java.time.YearMonth to org.joda.time.YearMonth and use the appropriate methods to convert to/from the desired type: (imports omitted):

@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);
  }
}
Community
  • 1
  • 1
Sebastian
  • 877
  • 1
  • 9
  • 20