Java中使用hql,sql查询返回的list 转成需要的实体对象--方法讲解!



需要将Query对象setResultTransformer:



List list = session.createSQLQuery(sql).setResultTransformer(

Transformers.ALIAS_TO_ENTITY_MAP).list();

//此时,每个Object可以转换成一个Map

Map map = (Map) list.get(i);

map.get("PARENT_ID");  //这里的key 一定是 数据库对应的字段名才行







例如:





// 查询出数据 

  String hql = "select a.id as emergencyBasExeId,a.LEVEL as level,a.SEND_TIME as sender_time,a.NAME as name,a.CONTENT as content " +

    ",a.PROCESS_ID as processId,m.STATES as states,m.id as id,m.emergencyInfoSecondMgr.id as emergencySencondMgrId " +

    " from EmergencyInfoFirstExe a,  EventManage m where a.deleteFlag = 0 and a.id=m.emergencyInfoFirstExe.id ";

  // 查询出数据list

  List exeList = eventManageDao.notifyHqlPage(hql, pageNumber * pageSize, pageSize);



  // 返回所需要的数据List

  List<EventInfoView> reList = new ArrayList<EventInfoView>();





  //map.get("PARENT_ID");  //这里的key 一定是 数据库对应的字段名才行 

  //对返回List的数据封装 

  for(Object exe : exeList){

   EventInfoView event = new EventInfoView();

   //此时,每个Object可以转换成一个Map 

   Map map=(Map)exe;

   //然后可以使用map.get("属性名");即可取值

   event.setId(map.get("id").toString());

   event.setContent(map.get("content").toString());

   event.setEmergencyBasExeId(map.get("emergencyBasExeId").toString());

   event.setEmergencySencondMgrId(map.get("emergencySencondMgrId").toString());

   event.setEmergencyTitle(map.get("emergencyTitle").toString());

   event.setLevel(map.get("level").toString());

   event.setName(map.get("name").toString());

   event.setProcessId(map.get("processId").toString());

   event.setProcessName(map.get("processName").toString());

   event.setSender_time(map.get("sender_time").toString());

   event.setStates(map.get("states").toString());

   //....

   reList.add(event);

  }

 

你可能感兴趣的:(object)