
1.查询所有记录,并以列表形式查询
DaoImpl
public PageBean queryByPage(String hql, List<Object> listobj, int pageSize, int page) {
try {
SQLQuery query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(hql);
final int offset = PageBean.countOffset(pageSize, page);
final int length = pageSize; for(int i =0;i <listobj.size();i++) {
if(listobj.get(i) instanceof java.sql.Date) {
query.setDate(i,(Date)listobj.get(i));
}else {
query.setParameter(i,listobj.get(i));
}
} query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list(); List<ZdwhModel> listbd=new ArrayList<ZdwhModel>();
ZdwhModel obj=null;
Object arrobj[]=null;
for(int i=0;i<list.size();i++){
arrobj=(Object[])list.get(i);
obj=new ZdwhModel();
BigDecimal decimal = (BigDecimal) arrobj[0];
obj.setId(decimal.longValue());
obj.setDic_type((String)arrobj[6]);
obj.setItem_code((String)arrobj[2]);
obj.setItem_name((String)arrobj[3]);
obj.setMemo((String)arrobj[4]);
listbd.add(obj);
}
//count
String countHql="select count(*) "+hql.substring(hql.indexOf("from"),hql.indexOf("order"));
query=null;
query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(countHql); for(int i =0;i <listobj.size();i++) {
if(listobj.get(i) instanceof java.sql.Date) {
query.setDate(i,(Date)listobj.get(i));
}else {
query.setParameter(i,listobj.get(i));
}
} List listcount = query.list(); int allRow = ((BigDecimal)listcount.get(0)).intValue();
final int currentPage = PageBean.countCurrentPage(page); int totalPage = PageBean.countTotalPage(pageSize, allRow);//
PageBean pageBean = new PageBean();
pageBean.setPageSize(pageSize);
pageBean.setAllRow(allRow);
pageBean.setTotalPage(totalPage);
pageBean.setCurrentPage(currentPage);
pageBean.setList(listbd);
pageBean.init();
return pageBean; } catch (Exception e) {
e.printStackTrace();
}
return null;
}
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()方法
public UserModel islogin(String dwdm,String uname, String upwd) {
String hql="from UserModel where uname=? and upwd=? and dwdm=?";
Query query=this.getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql);
query.setString(0, uname);
query.setString(1, upwd);
query.setString(2, dwdm);
return(UserModel)query.uniqueResult();
}