I'd like to know whether anyone 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.
Asked
Active
Viewed 6,935 times
22

OMG Ponies
- 325,700
- 82
- 523
- 502

S.D
- 275
- 2
- 10
2 Answers
13
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.

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
1
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..?

jabal
- 11,987
- 12
- 51
- 99
-
I did mean statement.setObject, thanks for pointing out. The best use case would be when our DAO needs to execute 5 different update statements. In such a case, having 5 distinct update methods introduces a lot of duplicate code since the only differences are the sql statements and arguments which can be dynamic. – S.D May 08 '11 at 17:26