SSH统计热卖商品(解决类型转换问题)

public List<SalesVolume> getHot(){
    Configuration config = new Configuration().configure();
    SessionFactory sessionFactory = config.buildSessionFactory();
    Session session = sessionFactory.openSession(); 
    String hql = "selecto.product.p_id as id,o.product.p_name as name ,o.product.p_picture as picture, count(*) as num"+
            "from edu.nju.desserthouse.model.Order as o group by o.product.p_id order by num desc";
    Query query = session.createQuery(hql);
    query.setMaxResults(4);
    List products = query.list();
    session.close();
    sessionFactory.close();
    if(products.size()>0)
        return products;
    return null;
}

虽然返回的是list的结构类型,但是hibernate 只能是object的数据类型

问题难点:如何将object转化为我们需要的数据类型?

/**
* 将统计得到的链表转为数据结构为SalesVolume的ArrayList
* @param products
*/
public void listTransform(List products){
  ArrayList<SalesVolume> salesVolumes = new ArrayList<SalesVolume>();
  Iterator iterator=products.iterator();
  while(iterator.hasNext()){
    /**
    *先通过迭代器转为object[]数组
    */
    Object[] obj=(Object[]) iterator.next();
    /**
    *再把数组中的元素转为我们需要的类型,通过构造函数构造出我们需要的数据类型,添加到ArrayList中
    */
    int id=Integer.parseInt(obj[0].toString());
    String name=obj[1].toString();
    String picture=obj[2].toString();
    int num=Integer.parseInt(obj[3].toString());
    SalesVolume salesVolume=new SalesVolume(id,name,picture,num);
    salesVolumes.add(salesVolume);
  }
  this.request().setAttribute("salesVolumeList", salesVolumes);
}

 

posted on 2013-12-23 13:20  SherryIsMe  阅读(223)  评论(0编辑  收藏  举报

导航