使用Spring中的jdbcTemplate 时,通过id查询不到结果时返回Incorrect result size: expected 1, actual 0
@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 DataAccessUtils.requiredSingleResult(results); }
DataAccessUtils.requiredSingleResult(results);这个方法
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(); }
结果返回0和大于一个都会抛出异常,我们使用这个方法是期望返回一个对象的,但是可能返回0,我们需要的是null而不是异常,可以使用DataAccessUtils.uniqueResult(query);方法
/ ** * 查询单个对象 * @param id * @return */ public User findUserById(Integer id) { String sql = "select * from tuser where id = ?"; List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class), id); return DataAccessUtils.uniqueResult(query); }
queryForMap使用如下方法
public Map<String, Object> findUserMap(Integer id) { String sql = "select * from tuser where id = ?"; Object[] args = new Object[]{id}; List<Map<String, Object>> results = jdbcTemplate.query(sql, args, new RowMapperResultSetExtractor<Map<String, Object>>(new ColumnMapRowMapper(), 1)); return DataAccessUtils.uniqueResult(results); }
java学习交流群:513650703
相关推荐
JdbcTemplate的jar包 内含: commons-logging-1.2.jar spring-beans-5.0.0.RELEASE.jar spring-core-5.0.0.RELEASE.jar spring-jdbc-5.0.0.RELEASE.jar spring-tx-5.0.0.RELEASE.jar 查询一行的内容,封装为...
jdbcTemplate-runtime-update 使用Spring Boot在运行时更改DataSources和JdbcTemplate 稍后,我将文件编辑为一个小型项目,并编写有用且详细的说明
Spring:JdbcTemplate使用指南 Spring:JdbcTemplate使用指南
@Autowired protected JdbcTemplate jdbcTemplate; /** SQL语句参数带名称的JDBC模版对象 */ protected NamedParameterJdbcTemplate namedParameterJdbcTemplate; /** 分页SQL语句创建对象 */ protected ...
JdbcTemplate 调用存储过程
JdbcTemplate是spring-jdbc提供的数据库核心操作类,那对JdbcTemplate进行事务控制呢?
使用Spring的JdbcTemplate实现分页功能
spring-jdbcTemplate实例工程
jdbcTemplate分页彻底解决,使用游标滚动jdbcTemplate分页彻底解决,使用游标滚动
数据库连接池(常用的4-5个)、分页查询(oracle,mysql,sqlserver等)、数据转码(空值、特定、列名等)、数据导出(Pdf,excel,html,rtf,xml等)、日志处理、启动jar加载校验机制、扩展Hib、JdbcTemplate等等...
JdbcTemplate使用就是JdbcTemplate的使用 再说两遍JdbcTemplate使用就JdbcTemplate的使用 20字够了
struts+spring +jdbctemplate demo http://knight-black-bob.iteye.com/blog/2262258
JdbcTemplate CRUD示例
chapter1: 一起来学Spring Boot | 第一篇:构建第一个Spring Boot工程 chapter2: 一起来学Spring Boot | 第二篇:Spring Boot配置详解 chapter3: 一起来学Spring Boot | 第四篇:整合Thymeleaf模板 chapter4: 一...
SpringJdbcTemplate封装工具包,包括规范model格式接口,封装SpringJdbcTemplate,实现分页,自适应多种数据库
提供了使用Spring的jdbcTemplate需要导入的五个jar包
简单的jdbcTemplate预编译、回调等
JdbcTemplate基本使用 JDBC已经能够满足大部分用户最基本的需求,但是在使用JDBC时,必须自己来管理数据库资源如:获取PreparedStatement,设置SQL语句参数,关闭连接等步骤。 JdbcTemplate是Spring对JDBC的...