1.查询所有记录,并以列表形式查询
DaoImpl
1 public PageBean queryByPage(String hql, List<Object> listobj, int pageSize, int page) { 2 try { 3 SQLQuery query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(hql); 4 final int offset = PageBean.countOffset(pageSize, page); 5 final int length = pageSize; 6 7 for(int i =0;i <listobj.size();i++) { 8 if(listobj.get(i) instanceof java.sql.Date) { 9 query.setDate(i,(Date)listobj.get(i)); 10 }else { 11 query.setParameter(i,listobj.get(i)); 12 } 13 } 14 15 query.setFirstResult(offset); 16 query.setMaxResults(length); 17 List list = query.list(); 18 19 List<ZdwhModel> listbd=new ArrayList<ZdwhModel>(); 20 ZdwhModel obj=null; 21 Object arrobj[]=null; 22 for(int i=0;i<list.size();i++){ 23 arrobj=(Object[])list.get(i); 24 obj=new ZdwhModel(); 25 BigDecimal decimal = (BigDecimal) arrobj[0]; 26 obj.setId(decimal.longValue()); 27 obj.setDic_type((String)arrobj[6]); 28 obj.setItem_code((String)arrobj[2]); 29 obj.setItem_name((String)arrobj[3]); 30 obj.setMemo((String)arrobj[4]); 31 listbd.add(obj); 32 } 33 //count 34 String countHql="select count(*) "+hql.substring(hql.indexOf("from"),hql.indexOf("order")); 35 query=null; 36 query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(countHql); 37 38 for(int i =0;i <listobj.size();i++) { 39 if(listobj.get(i) instanceof java.sql.Date) { 40 query.setDate(i,(Date)listobj.get(i)); 41 }else { 42 query.setParameter(i,listobj.get(i)); 43 } 44 } 45 46 List listcount = query.list(); 47 48 int allRow = ((BigDecimal)listcount.get(0)).intValue(); 49 final int currentPage = PageBean.countCurrentPage(page); 50 51 int totalPage = PageBean.countTotalPage(pageSize, allRow);// 52 PageBean pageBean = new PageBean(); 53 pageBean.setPageSize(pageSize); 54 pageBean.setAllRow(allRow); 55 pageBean.setTotalPage(totalPage); 56 pageBean.setCurrentPage(currentPage); 57 pageBean.setList(listbd); 58 pageBean.init(); 59 return pageBean; 60 61 62 } catch (Exception e) { 63 e.printStackTrace(); 64 } 65 return null; 66 }
ServiceImpl
public String getHql(Map<String, Object> map,List<Object> listobj){ String hql = ""; hql+=" order by id"; return hql; } public PageBean queryForPage(int pageSize, int page,Map<String, Object> map){ List<Object> listobj = new ArrayList<Object>(); String hql = getHql(map, listobj); PageBean pageben = zdwhdao.queryByPage(hql, listobj, pageSize, page); return pageben; }
2.预处理查询、并且查询结果 当确定返回的实例只有一个或者null时 用uniqueResult()方法
1 public UserModel islogin(String dwdm,String uname, String upwd) { 2 String hql="from UserModel where uname=? and upwd=? and dwdm=?"; 3 Query query=this.getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql); 4 query.setString(0, uname); 5 query.setString(1, upwd); 6 query.setString(2, dwdm); 7 return(UserModel)query.uniqueResult(); 8 }
时间: 2024-10-11 03:31:42