如何将sql DATE映射到LocalDate

时间:2016-06-12 21:52:28

标签: java jdbc timezone java-8 sqldatetime

我想在LocalDate列中存储DATE并保持不变。 DATELocalDate都是"本地"根据定义类型。因此, timezone 的概念不应以任何方式干扰。

下面的代码是一个最小的示例,它在内存数据库中创建一个带有DATE列的表。 maven工件com.h2database:h2:1.4.192必须位于类路径中。

首先,定义方法insertretrieve

static void insert(DataSource ds, String date) throws SQLException {
  try (Connection conn = ds.getConnection();
       Statement stmt = conn.createStatement()) {
    stmt.execute("CREATE TABLE people (id BIGINT NOT NULL AUTO_INCREMENT"
      + ", born DATE NOT NULL, PRIMARY KEY (id) );");
    stmt.execute("INSERT INTO people (born) VALUES ('" + 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()) {
      java.sql.Date retrieved = java.sql.Date.valueOf(rs.getString("born"));
      return retrieved.toLocalDate();
    }
    throw new IllegalStateException("No data");
  }
}

请注意,insert方法在单引号中使用toString的{​​{1}}值,因此Java™没有机会创建时区歧义。现在拨打LocalDate一次,然后多次insert,每次都使用不同的timzone设置:

retrieve

然后打印以下内容:

Inserted:  2015-05-20
Retrieved: 2015-05-20
Retrieved: 2015-05-19
Retrieved: 2015-05-18

如何编写public static void main(String[] args) throws Exception { DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test", "sa", "sa"); LocalDate born = LocalDate.parse("2015-05-20"); insert(ds, born.toString()); System.out.println("Inserted: " + born); for (int i : new int[]{-14, 0, 12}) { TimeZone z = TimeZone.getTimeZone(String.format("Etc/GMT%+02d", i)); TimeZone.setDefault(z); System.out.println("Retrieved: " + retrieve(ds)); } } 方法,使其返回与无条件相同的值,假设数据库表没有变化?

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:1)