How to map sql DATE to LocalDate

前端 未结 2 2051
深忆病人
深忆病人 2021-01-12 20:21

I want to store a LocalDate in a DATE column and retrieve it unchanged. Both DATE and LocalDate are \"local\" types by de

相关标签:
2条回答
  • 2021-01-12 21:08

    The following solution also works. I prefer the conversion via String in the accepted answer, because it avoids the timezone tinkering shown below. It may however not work the same way on all databases because some, e.g. Oracle, have a different definition of DATE.

    static LocalDate retrieve(DataSource ds) throws SQLException {
      try (Connection conn = ds.getConnection();
           Statement stmt = conn.createStatement();
           ResultSet rs = stmt.executeQuery("SELECT * FROM people limit 1")) {
        if (rs.next()) {
          ZoneId utc = ZoneId.of("UTC");
          TimeZone z = TimeZone.getTimeZone(utc);
          Calendar cal = Calendar.getInstance(z);
          java.sql.Date retrieved = rs.getDate("born", cal);
          long time = retrieved.getTime();
          java.util.Date utilDate = new java.util.Date(time);
          Instant instant = utilDate.toInstant();
          ZonedDateTime zdt = instant.atZone(utc);
          return zdt.toLocalDate();
        }
      }
      throw new IllegalStateException("No data");
    }
    

    The conversion via java.util.Date is outlined in this question, as suggested by user Tunaki: Missed opportunity to fix JDBC date handling in Java 8?

    0 讨论(0)
  • 2021-01-12 21:25

    I just tried the following modification to your retrieve method and it worked for me:

    The H2 documentation for the DATE Type says that it is

    The date data type. The format is yyyy-MM-dd.

    So, instead of your ...

    java.sql.Date retrieved = (java.sql.Date) rs.getObject("born");
    return retrieved.toLocalDate();
    

    ... I just used ...

    return LocalDate.parse(rs.getString("born"));
    

    ... and my code produced

    Inserted:  2015-05-20
    Retrieved: 2015-05-20
    Retrieved: 2015-05-20
    Retrieved: 2015-05-20
    
    0 讨论(0)
提交回复
热议问题