调用查询单个时,假设如果没有返回值,那么就会出现的异常信息
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
正确结果的大小:预计1,实际0 "
那么我们可以通过重写其原方法来实现不报错;
IJbdbcTemplate类(重写类)
import java.util.Collection;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
/**
* <p class="detail">
* 功能:重写jdbcTempLate工具,
* 覆盖queryForObject报org.springframework.dao.EmptyResultDataAccessException:
Incorrect result size: expected 1, actual 0 错误
* </p>
* @ClassName: IJdbcTemplate
* @version V1.0
* @date 2017-1-12
*/
public class IJdbcTemplate extends JdbcTemplate {
@Override
public <T> T queryForObject(String sql, RowMapper<T> rowMapper,Object[] args) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return IJdbcTemplate.requiredSingleResult(results);
}
public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
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();
}
}
Spring.xml文件中指定bean
<!-- 重写jdbcTemplate : 报null指针错误 -->
<bean id="jdbcTemplate" class="com.tsou.jar.base.dao.IJdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
BaseDao中,注入时塞入指定IjdbcTemplate
@Autowired
IJdbcTemplate jdbcTemplate;
这样就不会出现错误了;