[英]Spring JDBC Query add to map
I'm using the Spring JDBC Framework ( like here ) to obtain two columns from the database. 我正在使用Spring JDBC Framework( 如此处 )从数据库中获取两列。 I have used the 'Mapper' to implement 'RowMapper' class and I execute the query like this:
我已经使用'Mapper'实现了'RowMapper'类,并且执行了如下查询:
List<Entity> rows = template.query(sql, new EntityMapper());
This is my Mapper Class: 这是我的Mapper课程:
public class EntityMapper implements RowMapper<Entity> {
@Override
public Entity mapRow(ResultSet rs, int rowNum) throws SQLException {
Entity entity = new Entity();
entity.setID(rs.getString("ID"));
entity.setAccount(rs.getString("ACCOUNT"));
return entity;
}
Instead of storing the results of the query into a <List>
, I want to store them into a Map
- accountsById
I created in the same class. 我不想将查询结果存储到
<List>
,而是将它们存储到我在同一类中创建的Map
- accountsById
中。 I want the ID that goes into the Map to be my key so that I can obtain the Id's with getID()
我希望将进入Map的ID作为我的密钥,以便我可以通过
getID()
获得ID。
public List<String> getID() {
if (accountsByID.isEmpty()) {
return Collections.EMPTY_LIST;
} else {
return new ArrayList<String>(accountsByID.keySet());
}
}
How do I store my query rows into a map in spring and set ID
as key, with value being account
. 如何在Spring中将查询行存储到地图中并将
ID
设置为键,值设置为account
。
queryForList
returns a List of LinkedHashMap objects. queryForList
返回一个LinkedHashMap对象的列表。
In order to get Map We need to cast the result of queryForList
method like below 为了获取地图,我们需要转换
queryForList
方法的结果,如下所示
List list = template.queryForList(...);
for (Object o : list) {
Map m = (Map) o;
<your code here which uses Map objects>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.