Home > Software design >  Inject Date or LocalDate into SQL query via jdbcTemplate.query?
Inject Date or LocalDate into SQL query via jdbcTemplate.query?

Time:10-08

I had a simple query like:

select * from sometable where date = ?

I injected a LocalDate into query:

jdbcTemplate.query(QUERY, date);

Everything worked fine. After I moved my project with IDE to another PC, without any alterations, it started to throw exception:

nested exception is org.postgresql.util.PSQLException: 
Can't infer the SQL type to use for an instance of java.time.LocalDate. 
Use setObject() with an explicit Types value to specify the type to use.

I can use a workaround via converting LocalDate to Date:

jdbcTemplate.query(QUERY, java.sql.Date.valueOf(date));

but it does not seem right to me: I want to know the reason. What I checked so far:

  1. PostgreSQL version is the same (BTW tried upgrading to 14)
  2. JDK version is the same
  3. POM dependency for PostgreSQL is the same.

CodePudding user response:

java.time.LocalDate has been available since Java-8 whereas your JDBC driver is based on Java-7, and hence the problem. Upgrade the JDBC driver to the latest one (following) or at least to the one supporting minimum Java-8.

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.24</version>
</dependency>

Note: The java.util Date-Time API and its children are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

  • Related