1. 程式人生 > >用hibernate封裝工具類中的查詢方法

用hibernate封裝工具類中的查詢方法

 可以將以下的方法整合到工具類中,用於以後的使用

public List query(String hql,Object...object){//使用這個類的時候hql語句形式:from 類 where ...
	   //讀取總的配置檔案
	   Configuration configuration = new Configuration().configure();
	   //建立session工廠
	   SessionFactory sessionnFactory = configuration.buildSessionFactory();
	   Session session = null;
	   List list = null;
	   try{
	      s = sessionFactory.openSession();
	      Query query = s.createQuery(hql);
	      //先判斷是否有引數要繫結
	      if(object != null && object.length > 0){
		for(int i = 0;i<object.length;i++){
		    query.setString(i,object[i]);
		}
	      }
	      list = query.list();
	   }catch(Exception e){
		e.printStackTrace();
		throw new RuntimeException(e.getMessage());
	   }finally{
		if(s != null && s.isopen()){
		    s.close();
		}
	   }
	}