JDBC結果セットはLocalDateTimeをを取得します

ヤンKhonski:

私は、MySQLデータベースから行を取得するために、単純なクエリを実行します。私が取得ResultSetし、私はそれからのLocalDateTimeオブジェクトを取得する必要があります。私のDBテーブル。

CREATE TABLE `some_entity` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `title` varchar(45) NOT NULL,
  `text` varchar(255) DEFAULT NULL,
  `created_date_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

私はidで、いくつかのエンティティを取得する必要があります。

String SELECT = "SELECT ID, TITLE, TEXT, CREATED_DATE_TIME FROM some_entity WHERE some_entity.id = ?";
PreparedStatement selectPreparedStatement = connection.prepareStatement(SELECT);
try {
    selectPreparedStatement.setLong(1, id);
    ResultSet resultSet = selectPreparedStatement.executeQuery();
    if (resultSet.next()) {
        Long foundId = resultSet.getLong(1);
        String title = resultSet.getString(2);
        String text = resultSet.getString(3);
        LocalDateTime createdDateTime = null;// How do I retrieve it???
    }
} catch (SQLException e) {
    throw new RuntimeException("Failed to retrieve some entity by id.", e);
}
トマシュLinkowski:

これを取得してみjava.sql.Timestampた後、への変換LocalDateTime使用してTimestamp.toLocalDateTime

LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()

EDITは:としてゴード・トンプソンがで指摘した彼のコメント最近の十分なJDBCドライバで作業する場合、さらに良い解決策があります:

resultSet.getObject(4, LocalDateTime.class)

これは、冗長作成スキップjava.sql.Timestampインスタンス。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=171638&siteId=1