HSQLDB,LocalDateTime,JdbcTemplate

时间:2017-07-27 22:02:06

标签: java hsqldb jdbctemplate

我尝试使用HSQLDB和spring JDBC模板。它工作正常,直到我使用Java 8的LocalDateTime类。

我有这段代码:

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

在app后端我使用LocalDateTime。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:8)

您应该能够使用Timestamp.valueOf()LocalDateTime转换为java.sql.Timestamp来解决问题:

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