开发者

Java ResultSet, SetObject vs SetString/SetDate/etc

开发者 https://www.devze.com 2023-03-03 13:51 出处:网络
I\'d like to know whether any开发者_开发技巧one considers using PreparedStatement.setObject for all data types as bad practice when preparing a statement. A use case for this would be a DAO with a gen

I'd like to know whether any开发者_开发技巧one considers using PreparedStatement.setObject for all data types as bad practice when preparing a statement. A use case for this would be a DAO with a generic executeQuery() method which can be re-used for all queries without having to worry about its data types.


You can do so.

E.g.

preparedStatement = connection.prepareStatement(SQL_INSERT);
SqlUtil.setValues(preparedStatement, user.getName(), user.getPassword(), user.getAge());

with

public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
    for (int i = 0; i < values.length; i++) {
        preparedStatement.setObject(i + 1, values[i]);
    }
}

The JDBC driver will do the type checking. The only disadvantage is maybe the (minor) overhead, but this is negligible as compared to the better maintainable code you end up with. Also, most ORM frameworks like Hibernate/JPA also uses that deep under the covers.


The ResultSet interface has no setObject(..) methods. It has only an updateObject(..) method. Did you mean PreparedStatement.setObject(..) ?

In this case I think this is not a bad practice, but not even a nice solution. As for me I don't really understand the need for the "generic DAO". Could you explain this idea in more details..?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号