Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC result set retrieve LocalDateTime [duplicate]

I run a simple query to retrieve a row from a MySQL database. I get ResultSet and I need to retrieve a LocalDateTime object from it. My DB table.

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;

I need to retrieve some entity by 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);
}
like image 343
Yan Khonski Avatar asked Aug 01 '18 11:08

Yan Khonski


1 Answers

Try retrieving this as java.sql.Timestamp and then converting to LocalDateTime using Timestamp.toLocalDateTime:

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

EDIT: As Gord Thompson pointed out in his comment, there's an even better solution when working with a recent enough JDBC driver:

resultSet.getObject(4, LocalDateTime.class)

This skips creating a redundant java.sql.Timestamp instance.

like image 79
Tomasz Linkowski Avatar answered Oct 21 '22 22:10

Tomasz Linkowski