两种为hql设置参数的万能方法

----------------------------------------------------两种为hql设置参数的万能方法---------------------------------------------------------------------

1.        ?占位符方式

2.  publicListgetList(String hql, String[] params) {

3.       Session session = getSession();

4.       Queryquery= null;

5.       try{

6.           

7.           query= session.createQuery(hql);

8.           if(params!=null)

9.           {

10.              for(inti=0;i<params.length;i++) {

11.                  query.setString(i, params[i]);

12.              }

13.          }

14.          Listlist=query.list();

15.          if(list!=null&&list.size()!=0){

16.            

17.              returnlist;

18.          

19.          }

20.          

21.      } catch(Exception e) {

22.          e.printStackTrace();

23.          return null;

24.      } finally{

25.          try{

26.              if(session != null&& session.isOpen()) {

27.                  closeSession();

28.              }

29.          } catch(Exception e) {

30.              e.printStackTrace();

31.          }

32.      }

33.       return null;

34.     }

 二.:参数名方式

 publicListqueryList(String strHql, String[] paraName, Object[] paraValue, intpageNum, intnumPerPage)

    {

    

        Session session = null;

        Transaction tx = null;

        ListretList = null;

        try{

            session = getSession();

            tx = session.beginTransaction();

            Query q = session.createQuery(strHql);

            if(paraValue.length>0 && paraValue.length== paraName.length)

            {

                for(inti=0; i<paraValue.length; i++)

                {

                    if(strHql.indexOf(":"+ paraName[i]) != -1)

                    q.setParameter(paraName[i], paraValue[i]);

                }

            }

            if(pageNum != 0 && numPerPage != 0) {

                q.setFirstResult((pageNum - 1) * numPerPage);

                q.setMaxResults(numPerPage);

            }

            if(q.list() != null&& q.list().size() != 0) {

                retList = q.list();

            }

            tx.commit();

            q = null;

        } 

        catch(HibernateException e) 

        {

            try{

                tx.rollback();

            } catch(HibernateException e1) {

                e1.printStackTrace();

            }

            e.printStackTrace();

        }

        finally

        {

            try{

                   closeSession();

            } catch(HibernateException e) {

                e.printStackTrace();

                logger.error("Close sf session failed ....by message "+ e.getMessage());

            }

            tx = null;

            session = null;

        }

        

        returnretList;

    }

 

 

猜你喜欢

转载自zwfwgood.iteye.com/blog/1479657