- BaseDAO
需求:
按名字分页查询对应书籍信息
//hql查询通用方法
/**
* hql:
* 1、hql传过来,拼接countHql
* 2.给命名参数赋值
* 3、pagebean.settotal
* 4、查询你所需要的结果
*
* @author Administrator
*
*/
public class BaseDao {
/**
* 给命名参数赋值
* @param query
* @param map
*/
public void setParameters(Query query,Map<String, Object> map) {
if(map==null || map.size()==0) return;
Object value;
for (Map.Entry<String, Object> entry : map.entrySet()) {
value=entry.getValue();
if(value instanceof Collection) {
query.setParameter(entry.getKey(), (Collection)value);
}else if(value instanceof Object[]) {
query.setParameter(entry.getKey(), (Object[])value);
}else {
query.setParameter(entry.getKey(), value);
}
}
}
/**
* hql语句传过来,拼接countHql
* 用于查询符合条件的所有记录数
* @param hql
* @return
*/
private String getCountHql(String hql) {
int index=hql.toUpperCase().indexOf("FROM");
System.out.println("index"+index);
System.out.println("select count(*)" + hql.substring(index));
return "select count(*)" + hql.substring(index);
}
//@SuppressWarnings("deprecation")
protected List executeQuery(Session session,String hql,Map<String, Object> map,PageBean pageBean) {
if(pageBean !=null && pageBean.isPagination()) {
String countHql = getCountHql(hql);
Query countQuery = session.createQuery(hql);
this.setParameters(countQuery, map);
pageBean.setTotal(countQuery.getSingleResult().toString());
Query query = session.createQuery(hql);
this.setParameters(query, map);
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
return query.list();
}else {
Query query = session.createQuery(hql);
this.setParameters(query, map);
return query.list();
}
}
}
- 原生sql
hql实现不了的功能,可以考虑使用原生sql
1、多表(5+)联查
2、未配置映射文件中关系
//原生sql
public List<Book> list(Book book,PageBean pageBean){
Session sesstion = SessionFactoryUtils.getSesstion();
Transaction transaction = sesstion.beginTransaction();
String sql="select * from t_hibernate_book";
List list = sesstion.createNamedQuery(sql).list();
transaction.commit();
sesstion.close();
return list;
}
-
视图映射
场景
select * from 3表联查
SELECT @rowno:=@rowno + 1 AS rowno,a.* FROM tableName a,(SELECT @rowno:=0) b