1、创建BaseDao的作用
- 传参
- 通常分页
思路:
- 获取最大条目数 select count(*)hql.toupcase.indexof(“from”)
- 获取需要的查询的分页数据
query.setfirstResult
query.setfirstResult
代码分享:
package com.zking.eight.util;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.struts2.components.Else;
import org.hibernate.Session;
import org.hibernate.query.Query;
import util.PageBean;
public class BaseDao {
private void setParameter(Query query,Map<String,Object> map) {
if(map == null || map.size() == 0) {
return;
}
Object value = null;
for(Map.Entry<String, Object> entry:map.entrySet()) {
value = entry.getValue();
if(value instanceof Collection) {
query.setParameterList(entry.getKey(), (Collection) value);
}
else if(value instanceof Object[]) {
query.setParameterList(entry.getKey(), (Object[]) value);
}
else {
query.setParameterList(entry.getKey(), (Collection) value);
}
}
}
//from 关键字转换成小写
public String getCountHql(String hql) {
int index = hql.toUpperCase().indexOf("FROM");
return "select count(*)"+ hql.substring(index);
}
public List executeQuery(String hql,PageBean pageBean,Map<String , Object>map,Session session) {
//判断需不需要分页
if(pageBean !=null && pageBean.isPagination()) {
String countHql = getCountHql(hql);
Query countQuery = session.createQuery(countHql);
this.setParameter(countQuery, map);
String total = countQuery.getSingleResult().toString();
pageBean.setTotal(total);
//
Query pageQuery = session.createQuery(hql);
this.setParameter(pageQuery, map);
pageQuery.setFirstResult(pageBean.getStartIndex());
pageQuery.setMaxResults(pageBean.getRows());
return pageQuery.list();
}
else {
//不需要分页,查询所有
Query query = session.createQuery(hql);
this.setParameter(query, map);
return query.list();
}
}
public List eQy(String hql,PageBean pageBean,Map<String , Object> map,Session session) {
if(pageBean !=null && pageBean.isPagination()) {
String countHql = getCountHql(hql);
Query countQuery = session.createQuery(countHql);
this.setParameter(countQuery, map);
String total = countQuery.getSingleResult().toString();
pageBean.setTotal(total);
Query pageQuery = session.createQuery(hql);
this.setParameter(pageQuery, map);
pageQuery.setFirstResult(pageBean.getStartIndex());
pageQuery.setMaxResults(pageBean.getRows());
return pageQuery.list();
}
else {
Query query = session.createQuery(hql);
this.setParameter(query, map);
return query.list();
}
}
}
2、原生态sql
1、关系难配置
2、业务逻辑复杂
3、视图(对原生态sql增强)
业务逻辑复杂并重用