hibernate是按照hql語句來進行查詢的, 里面所使用的表名, 其實是實體類的名字, hql語句的寫法並沒有多大差別, 是在返回結果的時候要稍微做一些處理
//使用hibernate進行多表查詢, 返回一個list public List<?> getHfxx(BigDecimal id) { String hql = "select a.xchfsj,a.khjb,a.khly,b.jhhffs from CmKhxxb a,CmKhgzxxb b where a.khbh=b.khbh and a.id="+id; List<?> list = hiberTem.find(hql); return list; }
以上是查詢的方法, 返回了一個list, 接收數據的方法在下面
//點擊回訪客戶, 返回客戶信息表, 與上面的方法差不多, 只是返回給不同的標簽 @ResponseBody @RequestMapping(value="/getCmKhxx.do", method=RequestMethod.POST) public String getCmKhxx(@RequestParam(value="khid")String khid) { String json = "{\"success\":"; BigDecimal bId = new BigDecimal(khid); List<?> list = cmKhxxbDao.getHfxx(bId); Iterator<?> iter = list.iterator(); HashMap<String, String> map = null; while(iter.hasNext()) { Object[] o = (Object[])iter.next(); if(o!=null) { map = new HashMap<String, String>(); String hfsj = ""; try { hfsj = DateFormat.getStringDate((Date)o[0]); } catch (ParseException e) { e.printStackTrace(); } map.put("xchfsj", hfsj); map.put("khjb", (String)o[1]); map.put("khly", (String)o[2]); map.put("jhhffs", (String)o[3]); } } if(map==null) { json += "false}"; } else { json += "true,\"action\":"; json += JSON.toJSONString(map); json += "}"; } return json; }
在返回的這個list當中, 其實每一個對象都是按照你所寫的select后面的字段名的順序來的, 進行強轉可以轉換成功, 因為我是用的springMVC, 所以用了一個map來接收, 再進行JSON的轉換傳給前台, 上面代碼中的 DateFormat 是自己寫的一個日期轉換的靜態類, Date型的數據從數據庫中取來是一個時間戳的形式, 需要先轉換
hibernate進行多表關聯查詢有一點需要注意, 如果有一個表中沒有數據, 而在hql中加上了a.khbh = b.khbh諸如此類的條件, 返回的list就成了空