JdbcTemplate found a problem when it was used:
Call the queryForObject () method and throw an exception if nothing is found: org.springframework.dao.EmptyResultDataAccessException:Incorrect result size:expected 1, actual 0
You do not want to throw this exception, but return to null on the line.
See Source code
@Override public
<T> T queryforobject (String sql, rowmapper<t> rowmapper) throws DataAccessException { c2/>list<t> results = query (sql, rowmapper);
return Dataaccessutils.requiredsingleresult (results);
}
The result set in the source code returns a static method that calls Dataaccessutils, and spring makes a judgment in this static method:
public static <T> T Requiredsingleresult (collection<t> results) throws incorrectresultsizedataaccessexception {
int size = (results!= null? Results.size (): 0);
if (size = = 0) {
throw new emptyresultdataaccessexception (1);
}
if (Results.size () > 1) {
throw new incorrectresultsizedataaccessexception (1, size);
}
Return Results.iterator (). Next ();
We can write a class to inherit JdbcTemplate directly, rewrite the queryForObject () method, the result set ==0, return null;
The public class Overridejdbc extends jdbctemplate{/** * Rewrite JdbcTemplate inside the queryForObject method source Call Requiredsingleresult , returns NULL when the result of the query is empty (the original exception is thrown) */@Override public <T> T queryforobject (String sql, class<t> required
Type) throws DataAccessException {return queryforobject (SQL, Getsinglecolumnrowmapper (requiredtype)); } public <T> T queryforobject (String sql, rowmapper<t> rowmapper) throws DataAccessException {Li
st<t> results = query (sql, RowMapper);
return Requiredsingleresult (results); public static <T> T Requiredsingleresult (collection<t> results) throws Incorrectresultsizedataaccessexc
eption {int size = (results!= null? Results.size (): 0);
if (size = = 0) {return null;
} if (Results.size () > 1) {throw new Incorrectresultsizedataaccessexception (1, size);
Return Results.iterator (). Next (); }
}
Then inject datasource for this class OVERRIDEJDBC in spring's configuration file
"Note" If you used the JdbcTemplate and injected datasource into the spring configuration file, you would have a mistake if you injected another one.
You can comment out the JdbcTemplate bean as you write the Overridejdbc inherited JdbcTemplate, which is the same as the JdbcTemplate type, so you only recognize a bean when you use @autowired. More or less will be the error, I was this tangle of the afternoon time
<!-- <bean id= "jdbctemplate" class = "Org.springframework.jdbc.core.JdbcTemplate" >
<property Name= "DataSource" ref = "DataSource" ></property>
</bean>-->
<!-- Configure spring JDBC- >
<bean id= "Overridejdbc" class= "Com.dao.OverrideJdbc" >
<property name= "dataSource" ref = " DataSource "></property>
</bean>
After the configuration is ready to use, of course, jdbctemplate inside the other methods can also be rewritten to see personal needs.