问题
I understand that the OTHER data type can store any Serializable object. However when I try to store an instance of String or Boolean it fails with an exception.
Is this a misunderstanding on my part, or a bug in H2?
Here's repro code.
import org.h2.jdbc.JdbcSQLException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ScratchSpace {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
conn.createStatement().execute("drop table if exists test;");
conn.createStatement().execute("create table test (key VARCHAR, value OTHER)");
testInsert(conn, "key1", "foobar");
testInsert(conn, "key2", Boolean.TRUE);
testInsert(conn, "key3", new MyClass("foobar"));
conn.close();
}
private static void testInsert(Connection conn, String key, Serializable value) throws SQLException {
try (PreparedStatement statement = conn.prepareStatement("insert into test (key, value) values (?, ?)")) {
statement.setString(1, key);
statement.setObject(2, value);
statement.executeUpdate();
System.out.println("Insert of value={" + value + "} succeeded");
} catch (JdbcSQLException e) {
System.out.println("Insert of value={" + value + "} failed: " + e.getMessage());
e.printStackTrace();
}
}
public static class MyClass implements Serializable {
private final String s;
public MyClass(String s) {
this.s = s;
}
}
}
Here's a stack trace when I try to store String in the OTHER column:
org.h2.jdbc.JdbcSQLException: Hexadecimal string contains non-hex character: "foobar"; SQL statement:
insert into test (key, value) values (?, ?) -- (?1, ?2) [90004-188]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.util.StringUtils.convertHexToBytes(StringUtils.java:983)
at org.h2.value.Value.convertTo(Value.java:867)
at org.h2.table.Column.convert(Column.java:148)
at org.h2.command.dml.Insert.insertRows(Insert.java:143)
at org.h2.command.dml.Insert.update(Insert.java:114)
at org.h2.command.CommandContainer.update(CommandContainer.java:78)
at org.h2.command.Command.executeUpdate(Command.java:254)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:157)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:143)
at com.barbarysoftware.pokercopilot.ScratchSpace.testInsert(ScratchSpace.java:29)
at com.barbarysoftware.pokercopilot.ScratchSpace.main(ScratchSpace.java:19)
来源:https://stackoverflow.com/questions/31964209/h2-other-data-type-throws-exception-when-storing-string-or-boolean