class java.time.LocalTime cannot be cast to class java.sql.Time

194 views Asked by At

I get this error when doing a batch update using setObject(int, LocalTime) with the combination of url properties: rewriteBatchedStatements=true and useServerPrepStmts=true

This says that LocalDate, LocalDateTime and LocalTime have been fully supported since 2015 with JDBC 4.2, and I don't get the error without the above combination of url properties.

I don't see it listed as a bug fix (here, here, or here) but can anyone confirm whether this should indeed work and if so whether it's still broken (with the above combination of properties) in versions of Connector/J 8.0.29, 8.0.30 or 8.0.31? I upgraded from 8.0.26 to 8.0.28 for the same issue with LocalDate which was already reported and fixed about a year ago (mysql bug). And I see the same issue was reported/fixed about two years ago for LocalDateTime (mysql bug). I don't know, maybe this is a good time of year to report the same issue for LocalTime?

Example code:

//MySQL 5.7
//Connector/J 8.0.28

String url = "jdbc:mysql://localhost:3306/dbname? 
rewriteBatchedStatements=true&useServerPrepStmts=true";

String sql = "INSERT INTO time_test(time) VALUES(?)";

try (Connection con = DriverManager.getConnection(url, "root", "root");
    PreparedStatement ps = con.prepareStatement(sql) ) {

    con.setAutoCommit(false);

    for (int i = 0; i < 10; i++) {
        ps.setObject(1, LocalTime.now());
        ps.addBatch();
    }
    ps.executeBatch();
    con.commit();
} catch (Exception e) {
    e.printStackTrace();;
}

Exact error message:

java.lang.ClassCastException: class java.time.LocalTime cannot be cast to class java.sql.Time (java.time.LocalTime is in module java.base of loader 'bootstrap'; java.sql.Time is in module java.sql of loader 'platform') at com.mysql.cj.jdbc.ServerPreparedStatement.setOneBatchedParameterSet(ServerPreparedStatement.java:759) at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchedInserts(ClientPreparedStatement.java:712) at com.mysql.cj.jdbc.ClientPreparedStatement.executeBatchInternal(ClientPreparedStatement.java:426) at com.mysql.cj.jdbc.StatementImpl.executeBatch(StatementImpl.java:795) at com.test.Test.main(Test.java:24)

0

There are 0 answers