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

猜你喜欢

转载自blog.csdn.net/My_name_is_ZwZ/article/details/82860010