Hibernate多表联合查询解决办法

Hibernate多表联合查询解决办法

[ 2006-3-31 14:40:50 | By: 王宇飞 ]
http://www.tgrj.com/blog/user1/wangyufei/archives/2006/31.html

用Hibernate可能都会遇到这样的问题:多表联合查询返回的集合不能按通常的方式遍历,现将我的解决办法和大家分享一下,如果哪位有更好的办法请不吝赐教,谢谢!

 

/**
*制定一个类,该类的对象属性 obMap 将查询得到的每个字段的值存贮
*/

import java.util.TreeMap;

public class ListObject {
 private TreeMap   obMap;

 public TreeMap  getObMap() {
  return obMap;
 }

 public void setObMap(TreeMap  obMap) {
  this.obMap = obMap;
 }
}

 

  /**
  * 该类的对象将调用Session对象的方法对数据库进行各种操作
  */ 

public class ObjectHibernate{

................................................

  /**
  * 按条件查询记录(第一条记录位置,每次查询记录数)
  */
 public List findObject(int firstResult, int maxResults) {
  Session session = HibernateSessionFactory.currentSession();
  Transaction transaction = null;
  try {

   String strSql="select t.orderlistId ,t1.orderId,t1.orderTime," +
    " t.orderGoodsName ,t.orderGoodsCount from Orderlist t,Order t1 "+
    " where t.orderId=t1.orderId";
   transaction = session.beginTransaction();
   Query query = session.createQuery(strSql);
   if (query != null && query.list() != null
     && query.list().size() > 0) {
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);
    transaction.commit();
    session.flush();

    List list=query.list();

    List list1=new ArrayList();      //该集合将封装后的ListObject存贮,并返回

   if (list != null && list.size() > 0) {
      Iterator it = list.iterator();
      ListObject lo = null;
      TreeMap  treeMap = null;
      while (it.hasNext()) {
       Object ob[] = (Object[]) it.next();
       treeMap = new TreeMap();
       for (int i = 0; i          lo = new ListObject();
         treeMap.put(new Integer(i), ob[i]);
       }
    lo.setObMap(treeMap);
    list1.add(lo);
   }


    return list1; 
   } else {
    transaction.commit();
    session.flush();
    return null;
   }
  } catch (HibernateException e) {
   if (transaction != null)
    transaction.rollback();
   log.error(e);
   return null;
  } finally {
   if (session != null) {
    try {
     session.close();
    } catch (HibernateException e) {
     log.error(e);
     throw new RuntimeException(e);
    }
   }
  }
 }

..........................................................

 }

 

 

在Action中获得 ObjectHibernate类对象的 findObject(int firstResult, int maxResults)方法的返回值,并将该返回值放在HttpServletRequest中,取名为 ‘objectList’

 

 

 

 

 页面遍历 ListObject对象,并遍历其属性obMap(我用struts标签了)

..................................

  
       没有记录!!!
     

   
    
     
      
       
        
        =
        
       
      

     
    

   

你可能感兴趣的:(Java,技术专题)