JDBC ResultSet object types mapping has no Byte or Short? Why Integer only?

社会主义新天地 提交于 2019-12-10 10:29:36

问题


Good day. Can anyone explain why JDBC doesn't implement object mapping for some types. For example, Postgres JDBC has no Byte and Short mapping. I can get primitive byte and short, but in object format I can get only Integer.

This is source code from here

case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
    return getInt(columnIndex);

What's wrong wtih Byte and Short object types? How can I work with TINYINT, SMALLINT and so on.

What's problem to implement getByte and getShort similar to getInt


回答1:


The answer is in the JDBC™ 4.1 Specification JSR 221 on page 187

Note – The JDBC 1.0 specification defined the Java object mapping for the SMALLINT and TINYINT JDBC types to be Integer. The Java language did not include the Byte and Short data types when the JDBC 1.0 specification was finalized. The mapping of SMALLINT and TINYINT to Integer is maintained to preserve backwards compatibility.




回答2:


Backward compatibility to JDBC Specification 1.0 don't let to add Byte and Short object types in JDBC drivers. There is only one solution: 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;
}

Or

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

And

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 {
        // ...
    }

    // ...

}


来源:https://stackoverflow.com/questions/46005762/jdbc-resultset-object-types-mapping-has-no-byte-or-short-why-integer-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!