如何使用JDBCTemplate.queryForMap获取Map数据 [英] How to get Map data using JDBCTemplate.queryForMap
问题描述
如何从 JDBCTemplate.queryForMap()
加载数据并返回Map接口。如何在map内部维护查询数据。我试图加载但是我得到了低于异常,即 org.springframework.dao.IncorrectResultSizeDataAccessException:结果不正确
How to load data from JDBCTemplate.queryForMap()
and it returns the Map Interface.How the maintained the query data internally in map.I trying to load but i got below exception i.e., org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result
代码: -
public List getUserInfoByAlll() {
List profilelist=new ArrayList();
Map m=new HashMap();
m=this.jdbctemplate.queryForMap("SELECT userid,username FROM USER");
Set s=m.keySet();
Iterator it=s.iterator();
while(it.hasNext()){
String its=(String)it.next();
Object ob=(Object)m.get(its);
log.info("UserDAOImpl::getUserListSize()"+ob);
}
return profilelist;
}
Plz帮帮我
推荐答案
queryForMap
是合适的。你选择没有 where
子句,所以你可能想要 queryForList
。该错误可能表明 queryForMap
需要一行,但您查询的是检索多行。
queryForMap
is appropriate if you want to get a single row. You are selecting without a where
clause, so you probably want to queryForList
. The error is probably indicative of the fact that queryForMap
wants one row, but you query is retrieving many rows.
查看文档。 queryForList
只需要sql;返回类型是
Check out the docs. There is a queryForList
that takes just sql; the return type is a
列表< Map< String,Object>>
。
所以一旦你得到了结果,你就可以做你正在做的事情。我会做类似的事情
So once you have the results, you can do what you are doing. I would do something like
List results = template.queryForList(sql);
for (Map m : results){
m.get('userid');
m.get('username');
}
我会让你填写细节,但我不会迭代在这种情况下的键。我喜欢明确我期待的内容。
I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.
如果你有一个用户
对象,你真的想要加载用户实例,你可以使用 queryForList
来获取sql和类类型
If you have a User
object, and you actually want to load User instances, you can use the queryForList
that takes sql and a class type
queryForList(String sql,Class< T> elementType)
(自从我离开Javaland以来,Spring已经发生了很大变化。)
(wow Spring has changed a lot since I left Javaland.)
这篇关于如何使用JDBCTemplate.queryForMap获取Map数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!