Missed opportunity to fix JDBC date handling in Java 8?

后端 未结 2 1013
孤街浪徒
孤街浪徒 2020-12-05 02:03

Can any Java 8 + JDBC expert tell me if something\'s wrong in the following reasoning? And, if in the secrets of Gods, why this hasn\'t been done?

A java.sql.D

2条回答
  •  無奈伤痛
    2020-12-05 02:18

    To represent the date 2015-09-13 in database, we're thus forced to choose a timezone, parse the string "2015-09-13T00:00:00.000" in that timezone as a java.util.Date to get a millisecond value, then construct a java.sql.Date from this millisecond value, and finally call setDate() on the prepared statement, passing a Calendar holding the timezone chosen in order for the JDBC driver to be able to correctly recompute the date 2015-09-13 from this millisecond value

    Why? Just call

    Date.valueOf("2015-09-13"); // From String
    Date.valueOf(localDate);    // From java.time.LocalDate
    

    The behaviour will be the correct one in all JDBC drivers: The local date without timezone. The inverse operation is:

    date.toString();    // To String
    date.toLocalDate(); // To java.time.LocalDate
    

    You should never rely on java.sql.Date's dependency on java.util.Date, and the fact that it thus inherits the semantics of a java.time.Instant via Date(long) or Date.getTime()

    So, haven't we missed a huge opportunity to clean up the mess in JDBC while still maintaining backward compatibility? [...]

    It depends. The JDBC 4.2 spec specifies that you are able to bind a LocalDate type via setObject(int, localDate), and to fetch a LocalDate type via getObject(int, LocalDate.class), if the driver is ready for that. Not as elegant as more formal default methods, as you suggested, of course.

提交回复
热议问题