美好的一天。任何人都可以解释为什么JDBC没有为某些类型实现对象映射。例如,Postgres JDBC没有字节和短映射。我可以得到原始字节和短字,但在对象格式中我只能得到整数。
这是来自here
的源代码case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return getInt(columnIndex);
字节和短对象类型有什么问题?我如何使用TINYINT,SMALLINT等。
实施类似于getInt的getByte和getShort的问题
答案 0 :(得分:3)
答案在JDBC™ 4.1 Specification JSR 221 第187页
注意 - JDBC 1.0规范定义了Java对象映射 SMALLINT和TINYINT JDBC类型为Integer。 Java语言 在JDBC 1.0中没有包含Byte和Short数据类型 规范最终确定。 SMALLINT和TINYINT的映射到 维护整数以保持向后兼容性。
答案 1 :(得分:0)
向JDBC Specification 1.0的向后兼容性不允许在JDBC驱动程序中添加Byte和Short对象类型。只有一个解决方案:java crutch。
static public Integer getInteger(final ResultSet rs, final String columnName) throws SQLException {
final int value = rs.getInt(columnName);
return rs.wasNull() ? null : value;
}
或者
public <T> T getObjectValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
final T value = rs.getObject(columnName, clazz);
return rs.wasNull() ? null : value;
}
和
public final class ResultSetWrapper {
private final ResultSet rs;
public ResultSetWrapper(final ResultSet rs) {
this.rs = rs;
}
public ResultSet getResultSet() {
return rs;
}
public Boolean getBoolean(String label) throws SQLException {
// ...
}
public Byte getByte(String label) throws SQLException {
// ...
}
public Byte getShort(String label) throws SQLException {
// ...
}
// ...
}