Hibernate使用hql和sql查询

一般情况下,程序里写了实体类(TestEntity.java)以及实体类和hibernate的映射文件(TestEntity.hbm.xml),那么在写操作数据库语句时,会使用hql,直接操作实体类,很方便且不容易出错,写法:

一般查询:可以一次写完整个hql语句,需要传递的参数预留出位置,后面用query.set*()放进去,再执行this.execFoQuery(query)就可以了:

public class TestDao extends FoHibernateDaoSupport implements ITestDao{
	public TestEntity findTestListById(Integer id) {
		FoHQLQuery query = new FoHQLQuery("from TestEntity a where a.testId=:ID");
		query.setLong("ID", id);
		return (TestEntity) this.execFoQuery1(query);
	}
}

分页查询,是不是很方便,只要告诉它每页多少条,第多少页就可以,前端搭配EasyUI等框架,写起来很方便,使用execFoPageQuery:

public class TestDao extends FoHibernateDaoSupport implements ITestDao{
	public FoPage findTestList(TestEntity entity, int pageNum, int pageSize) {
		FoHQLQuery query = new FoHQLQuery();
		String hql = "from TestEntity a  where 1=1 ";
		if (entity.getId()!=null && !"".equals(entity.getId().trim())){
			hql=hql +" and a.Id=:ID";
			query.setString("ID", entity.getId());
		}
		if ((entity.getStartTime()!=null)&&(!entity.getStartTime().equals(""))){
			hql=hql +" and a.startTime >='"+entity.getStartTime()+"'";
		}
		if ((entity.getEndTime()!=null)&&(!entity.getEndTime().equals(""))){
			hql=hql +" and a.startTime <='"+entity.getEndTime()+"'";
		}
		hql += " order by a.startTime desc";
		query.setHQL( hql );
		query.setPageNum( pageNum );
		query.setpageSize( pageSize );				
		return this.execFoPageQuery( query );
	}
}

保存删除对象,直接保存对象,是不是很方便,不用像写sql那样把每个字段insert进去,使用this.getHibrenateTemplete():

public class TestDao extends FoHibernateDaoSupport implements ITestDao{		
	public void saveTest(TestEntity entity) {
		this.getHibernateTemplate().save(entity);		
	}	
	public void delTest(TestEntity entity) {
		this.getHibernateTemplate().delete(entity);
	}
}

但是,并不是所有的查询会需要实体类的映射,假如有一些情况下,直接使用 sql会更方便些,那现有的工程里的Hibernate怎么执行sql呢:

package com.test.dao;
import java.util.List;
import com.sys.dao.FoHibernateDaoSupport;

public class SqlTestDao extends FoHibernateDaoSupport  {
	public int findTotalNum(String startTime) {		
		String sql = "select t.Id from OtherEntity t where t.startTime >= '" +
				startTime + "' and t.responseTime is not null";
		List list = (List)this.getHibernateTemplate().find(sql);
		if(list == null){
			return 0;
		}
		return list.size();
	}
}

其中,execFoQuery()是:

package com.sys.dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class FoHibernateDaoSupport extends HibernateDaoSupport{
  public FoPage execFoPageQuery(FoQuery foQuery){
    if (foQuery instanceof FoHQLQuery){
      return execFoPageHQLQuery((FoHQLQuery)foQuery);
    }if (foQuery instanceof FoSQLQuery){
      return execFoPageSQLQuery((FoSQLQuery)foQuery);
    }if (foQuery instanceof FoNamedQuery){
      return execFoPageNamedQuery((FoNamedQuery)foQuery);
    }
    return null;
  }

  public List execFoQuery(FoQuery foQuery){
    if (foQuery instanceof FoHQLQuery){
      return execFoHQLQuery((FoHQLQuery)foQuery);
    }if (foQuery instanceof FoSQLQuery){
      return execFoSQLQuery((FoSQLQuery)foQuery);
    }if (foQuery instanceof FoNamedQuery){
      return execFoNamedQuery((FoNamedQuery)foQuery);
    }
    return null;
  }

  public int execFoUpdate(FoQuery foQuery){
    Integer i = null;
    if (foQuery instanceof FoHQLQuery){
      i = execFoHQLUpdate((FoHQLQuery)foQuery);
    } else if (foQuery instanceof FoSQLQuery){
      i = execFoSQLUpdate((FoSQLQuery)foQuery);
    } else if (foQuery instanceof FoNamedQuery){
      i = execFoNamedUpdate((FoNamedQuery)foQuery);
    }
    return i.intValue();
  }

  public Object execFoQuery1(FoQuery foQuery){
    List list = execFoQuery(foQuery);
    if ((list == null) || (list.size() == 0)) {
      return null;
    }
    return list.get(0);
  }

  private FoPage execFoPageHQLQuery(FoHQLQuery foQuery){
    return (FoPage)getHibernateTemplate().execute(
      new HibernateCallback(foQuery){
      public Object doInHibernate(Session session) throws HibernateException{
        FoPage foPage = new FoPage();
        int nPageSize = this.val$foQuery.getPageSize();
        if (nPageSize <= 0) {
          nPageSize = 10;
        }
        int nPageNum = this.val$foQuery.getPageNum();
        if (nPageNum <= 0) {
          nPageNum = 1;
        }
        foPage.setPageSize(nPageSize);
        foPage.setPageNum(nPageNum);
        int totalCount = 0;
        if (this.val$foQuery.getCountHQL() != null){
          totalCount = ((Number)this.val$foQuery.fillQueryStmt(
            session.createQuery(this.val$foQuery.getCountHQL()))
            .uniqueResult()).intValue();
          foPage.setTotalRecordCount(totalCount);
        }else{
          throw new HibernateException("没有找到统计总数的HQL");
        }
        if ((nPageNum - 1) * nPageSize >= totalCount){
          foPage.setPageNum(foPage.getPageCount());
          nPageNum = foPage.getPageNum();
        }
        foPage.setDataList(
          this.val$foQuery.fillQueryStmt(session.createQuery(this.val$foQuery.getHQL()))
          .setFirstResult((nPageNum - 1) * nPageSize).setMaxResults(nPageSize)
          .list());
        return foPage;
      }
    });
  }
}



你可能感兴趣的:(Hibernate使用hql和sql查询)