Java journey 2022-01-26 11:21:02 阅读数:562
JdbcTemplate As a common way to interact with the database , It's very convenient to use . But when the query result is map It is required that the query result has and only has one piece of data . Next, let's see how the source code is handled .
Focus on the third screenshot , How to handle query results , If the query result is empty , be throw new EmptyResultDataAccessException(1);, If the result is greater than 1 strip , be throw new IncorrectResultSizeDataAccessException(1, results.size());
Let's look at these two exceptions , Find out EmptyResultDataAccessException yes IncorrectResultSizeDataAccessException A subclass of .
When this exception is thrown , What we see on the console is the statement printed by the following method .
that , How to be in Dao How to deal with this layer , Because we will be in service Processing transactions in , All will dao The anomaly of the layer is thrown to service, But the query map Null is reasonable , So we usually catch EmptyResultDataAccessException,map For multiple pieces of data, we think it is unreasonable , Usually throw it out , Next, let's look at the code written , In general, we only catch EmptyResultDataAccessException , return null.IncorrectResultSizeDataAccessException We don't catch exceptions , It will be thrown directly and returned to the front-end page after processing .
Generally, we can deal with business requirements by writing like this , In the actual development, it should be handled according to the specific business .
copyright:author[Java journey],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261120594996.html