hibernate的hql2

  1. 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();
		}
		
	}
}

  1. 原生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;
	
}
  1. 视图映射

    场景
    select * from 3表联查

SELECT @rowno:=@rowno + 1 AS rowno,a.* FROM tableName a,(SELECT @rowno:=0) b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值