英文:
From query i wil get 2 rows but while returing the map i am not getting 2 rows i am getting only last row
问题
// 在这个方法中,我通过查询从数据库获取数据,我得到了2行数据,但在返回映射时,我只得到了最后一行
public Map<Integer, String> getname(int id) {
Session session = sessionFactory.openSession();
// 创建映射
Map<Integer, String> stylesMap = new LinkedHashMap<Integer, String>();
try {
    Query query = getSession().createSQLQuery("select distinct id,name from employee where id=" + id);
    List results = query.list();
    Iterator itr = results.iterator();
    // 遍历值
    while (itr.hasNext()) {
        Object row1[] = (Object[]) itr.next();
        // 将值设置到映射中
        stylesMap.put(row1[0] == null ? 0 : Integer.parseInt(row1[0].toString()), (row1[1] == null) ? "" : row1[1].toString());
    }
} catch (Exception e) {
    logger.error("", e);
} finally {
    if (session != null) {
        session.close();
    }
}
// 返回映射
return stylesMap;
}
英文:
// i created on method in that i am getting data from database through query , i am getting 2 rows but while returning the map i am not getting 2 rows it returning only last row
    public Map<Integer, String> getname(int id) {
    			
    			Session session = sessionFactory.openSession();
    //creating map
    			Map<Integer,String> stylesMap = new LinkedHashMap <Integer,String>();
    			try {
    				
    	   Query query=getSession().createSQLQuery("select distinct id,name from employee where id="+id);
    				
          	List results = query.list();
    		Iterator itr = results.iterator();
    //iterating the values
    
    		while (itr.hasNext()) {
    		 Object row1[] = (Object[]) itr.next();
    //setting values into map
    		stylesMap.put(row1[0]==null?0:Integer.parseInt(row1[0].toString()), (row1[1] == null)? "" : row1[1].toString());
    				}
    			}catch (Exception e) {
    				logger.error("", e);
    			} finally{
    				if(session !=null) {
    					session.close();
    				}
    			}
// returning map
    	return stylesMap;
}
答案1
得分: 0
你的数据库返回了两行数据:
7 1
7 2
你试图将这些信息存储在一个映射中,但由于映射只能为一个键存储一个值,第一个值将被覆盖。
如果你的数据库包含两个相同ID的记录(理想情况下不应该出现这种情况),那么你可以将这些信息存储在以下方式之一:
- 
一个 pairs 列表,类似于
List<Pair<int,int>> - 
或者你可以创建一个 EmployeeDTO
public class EmployeeDTO{ String id; String name; }然后你可以将你得到的结果存储在一个
List<EmployeeDTO>中。 
英文:
Your DB returns two rows with data
7 1
7 2
You are trying to store this information in a map, but since a map stores only one value for a key, the first one will be overwritten.
If your DB contains two records for the same id( which ideally should not be the case), then you can store this information in
- 
A list of pairs, something like
List<Pair<int,int>> - 
Or you can create an EmployeeDTO
public class EmployeeDTO{ String id; String name; }And you can store the results you got in a
List<EmployeeDTO> 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论