栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

9.1,spring Template将查询的结果封装成map,list,bean的list

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

9.1,spring Template将查询的结果封装成map,list,bean的list

1.map

 注意:这个方法查询的结果集长度只能是1
 String sql = "select * from emp where id = ? or id = ?";
				        Map map = template.queryForMap(sql, 1001,1002);
				        System.out.println(map);
				        //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

2.list

String sql = "select * from emp";
				        List> list = template.queryForList(sql);
				
				        for (Map stringObjectMap : list) {
				            System.out.println(stringObjectMap);
				        }

3.类的集合

String sql = "select * from emp";
		        List list = template.query(sql, new RowMapper() {//匿名内部类,重写这个方法
		
		            @Override
		            public Emp mapRow(ResultSet rs, int i) throws SQLException {
		                Emp emp = new Emp();
		                int id = rs.getInt("id");
		                String ename = rs.getString("ename");
		                int job_id = rs.getInt("job_id");
		                int mgr = rs.getInt("mgr");
		                Date joindate = rs.getDate("joindate");
		                double salary = rs.getDouble("salary");
		                double bonus = rs.getDouble("bonus");
		                int dept_id = rs.getInt("dept_id");
		
		                emp.setId(id);
		                emp.setEname(ename);
		                emp.setJob_id(job_id);
		                emp.setMgr(mgr);
		                emp.setJoindate(joindate);
		                emp.setSalary(salary);
		                emp.setBonus(bonus);
		                emp.setDept_id(dept_id);
		
		                return emp;
		            }
		        });
		
		
		        for (Emp emp : list) {
		            System.out.println(emp);
		        }

用实现类来封装成list,非常方便

String sql = "select * from emp";
				        List list = template.query(sql, new BeanPropertyRowMapper(Emp.class));
				        for (Emp emp : list) {
				            System.out.println(emp);
				        }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号