JDBC get/setObject vs. get/setSpecificType
JDBC ResultSet 开发者_JAVA百科offers getObject, getInt, getString etc. methods, and PreparedStatement has analogous setters. Apart from type compile-time type safety, do the type specific getters/setters have any (dis)advantages, or is it OK to use getObject/setObject everywhere?
There are no real technical (dis)advantages. They may only be functionally disadvantageous if you're doing typechecking/casting yourself afterwards.
I myself use ResultSet#getObject()
only when the returned value is a primitive which is DB-defaulted to NULL
and the declared value is a wrapper for the primitive. E.g. Integer age
:
user.setAge(resultSet.getObject("age") != null ? resultSet.getInt("age") : null);
And I use PreparedStatement#setObject()
practically all the time, in an utility method:
public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
preparedStatement.setObject(i + 1, values[i]);
}
}
精彩评论