M
M
mitaichik2017-01-26 18:01:09
Java
mitaichik, 2017-01-26 18:01:09

JdbcTemplate: how to correctly select one object?

Task: you need to return an object from the database or null if it is not found
. There is a JdbcTemplate.queryForObject. If there is no record, it will throw an exception. To return null, it is recommended to simply catch this exception and return null, but it seems to me that this is not the best way.
There is this method: query(String sql, ResultSetExtractor rse), but for some reason it calls ResultSetExtractor.extractData even if the database returned 0 rows.
In general - tell me how to do it right. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-01-27
@dsv

It all depends on your specific needs and/or preferences. It may be more convenient for someone to catch the SqlException outside the method that receives the data, and for someone to get null and understand that the record was not found.
In queryForObject, you can simply pass a mapper and not think about processing each ResultSet entry.
And in ResultSetExtractor, without Exception, you can handle the situation of both the absence of found records and the receipt of several records if only one was expected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question