1. 程式人生 > >Hibernate中query的常用方法

Hibernate中query的常用方法

/**
* 查詢一個屬性
*/
public List getoneProperty(){
   List arr=new ArrayList();
   try {
    String hql="select s.SName from Stu as s";
    Query query=this.GetSession().createQuery(hql);
    Iterator iter=query.iterate();
    while(iter.hasNext()){
     Object obj=(Object) iter.next();
     Stu s=new Stu();
     s.setSName(obj.toString());
     arr.add(s);
    }
   } catch (HibernateException e) {
    this.CloseSession();
   }
   return arr;

}

/**
* SQL查詢
*/
public List getallBYSQL(){
   List arr=null;
   try {
    String sql="select {c.*} from stu as c";
    SQLQuery sqlquery=this.GetSession().createSQLQuery(sql);
    sqlquery.addEntity("c",Stu.class);
    arr=sqlquery.list();
   } catch (HibernateException e) {
    throw e;
   }finally{
    this.CloseSession();
   }
   return arr;
}

/**
* 模糊查詢
*/
public List getallQueryLike(String name){
   List arr=null;
   try {
    String hql="from Stu as s where s.SName like :name";
    Query query=this.GetSession().createQuery(hql);
    query.setString("name", "%"+name+"%");
    //不能
    //query.setString("name", "'%"+name+"%'");
    arr=query.list();
   } catch (HibernateException e) {
    throw e;
   }finally{
    this.CloseSession();
   }
   return arr;
}

  /**
* 條件統計
*/
public int CountByWhere(String sex){
   int count=0;
   try {
    Query query=this.GetSession().createQuery("select count(*) from Stu where SSex=:sex");
    query.setString("sex", sex);
    count=(Integer)query.uniqueResult();
   } catch (HibernateException e) {
    throw e;
   }finally{
    this.CloseSession();
   }
   return count;
}