Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HSQLDB, LocalDateTime, JdbcTemplate

I'm trying to use the HSQLDB, together with spring JDBC template. It works fine, until I use Java 8's LocalDateTime class.

I have this code:

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());
        }
    }

The script looks like this:

CREATE TABLE test
(
  datetime DATETIME NOT NULL,
);

When I try to run it, I'll get the exception:

org.hsqldb.HsqlException: incompatible data type in conversion

In the app backend I use LocalDateTime. How can I make this work?

like image 887
BadQuestion Avatar asked Jul 27 '17 22:07

BadQuestion


1 Answers

You should be able to work around the problem by converting the LocalDateTime into a java.sql.Timestamp using Timestamp.valueOf():

JdbcTemplate template = new JdbcTemplate(dataSource);
template.update("INSERT INTO test VALUES (?)",  Timestamp.valueOf(LocalDateTime.now()));
like image 109
Mick Mnemonic Avatar answered Sep 22 '22 12:09

Mick Mnemonic