Reputation: 11
Is it advisable to use JDBCTemplate
and NamedParameterJdbcTemplate
together with an idea that NamedParameterJdbcTemplate
is used for inserting/updating while JdbcTemplate
takes care of retrieving and deleting? Because I can insert objects by using NamedParameterJdbcTemplate
as simple as shown below:
public long save(Domain obj) {
String sql = "insert into domain(name,password,salt,dnspod_domain_id,status)" +
" values(:name,:password,:salt,:dnspodDomainId,:status)";
KeyHolder keyHolder = new GeneratedKeyHolder();
namedJdbc.update(sql, new BeanPropertySqlParameterSource(obj), keyHolder);
return keyHolder.getKey().longValue();
}
If I want to insert objects/data into table by using JDBCTemplate
, I will have to write lot of code manually assigning parameters with PreparedStatement
...
When it comes to retrieving, I can do it by JDBCTemplate
as shown below:
List<User> users = jdbcTemplate.query("SELECT * FROM user", BeanPropertyRowMapper.newInstance(User.class));
No need to use ResultSet
along with RowMapper
to retrieve rows.
My concern is that if there are any performance issues using JDBCTemplate
and NamedParameterJdbcTemplate
together.
Upvotes: 1
Views: 7516
Reputation: 2477
You can use both JdbcTemplate
and NamedParameterJdbcTemplate
whenever it is needed. JdbcTemplate
is slightly error-prone, since the order of "?" placeholders present in query and order of parameters you are passing through either array or direct setting is matter.
Where as NamedParameterJdbcTemplate
allows you to assign names to parameters and map values to the parameters by name, does't matter which order you set the values.
As per NamedParameterJdbcTemplate
api doc,
This class delegates to a wrapped JdbcTemplate once the substitution from named parameters to JDBC style '?' placeholders is done at execution time.
So internally api takes some additional time to convert Named params to `?' place holders, but this can be ignored.
My suggestion is if your query has too many parameters go with NamedParameterJdbcTemplate
, since its safe and error free else go with JdbcTemplate
.
Upvotes: 4