thatsIch thatsIch - 3 months ago 18
SQL Question

Mapping from java.time.MonthDay to java.sql.*

We have a case, where we require only the day and the month and thus would use the

java.time.MonthDay
(Javadocs) to represent that information.

We are aware that we could create our own JPA object for persistence or just use the
java.sql.Date
object, but that generally requires an unrequired year information.
Another way is to call the method
.atYear(int)
(Javadoc) (with a fictitious year) on it and receive a
java.time.LocalDate
(Javadoc), which can be easily converted to
java.sql.Date
. But this is prone to missunderstandings in the future (and also persist the year information).

Is there some "elegant"/supposed solution for this case? Or is there a replacement for SQL that supports the whole new date and time API for Persistence.

Another case would be
java.time.YearMonth
(Javadoc).

Thanks for reading!

Answer

Since SQL databases don't have a type compatible with MonthDay, use a VARCHAR columns, and simply use toString() and MonthDay.parse().

Or use a custom DateTimeFormatter, if you don't like the --12-03 format.

The default format will correctly sort, as a string.