HSQLDB、本地日期时间、JdbcTemplate

HSQLDB, LocalDateTime, JdbcTemplate

我正在尝试将 HSQLDB 与 spring JDBC 模板一起使用。它工作正常,直到我使用 Java 8 的 LocalDateTime class。

我有这个代码:

import org.hsqldb.jdbc.JDBCDataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import java.time.LocalDateTime;

    public class Test
    {
        public static void main(String[] args) throws Exception
        {
            JDBCDataSource dataSource = new JDBCDataSource();
            dataSource.setUser("SA");
            dataSource.setPassword("");
            dataSource.setUrl("jdbc:hsqldb:mem:db");

            Resource resource = new ClassPathResource("/test.sql");
            ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
            databasePopulator.execute(dataSource);

            JdbcTemplate template = new JdbcTemplate(dataSource);
            template.update("INSERT INTO test VALUES (?)",  LocalDateTime.now());
        }
    }

脚本如下所示:

CREATE TABLE test
(
  datetime DATETIME NOT NULL,
);

当我尝试 运行 它时,我会得到异常:

org.hsqldb.HsqlException: incompatible data type in conversion

在应用程序后端,我使用 LocalDateTime。我怎样才能使这项工作?

您应该可以通过使用 Timestamp.valueOf():

LocalDateTime 转换为 java.sql.Timestamp 来解决该问题
JdbcTemplate template = new JdbcTemplate(dataSource);
template.update("INSERT INTO test VALUES (?)",  Timestamp.valueOf(LocalDateTime.now()));