IT源码网

Hibernate多表联合查询解决办法

sanshao 2021年04月03日 程序员 376 0
**
*制定一个类,该类的对象属性 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 <ob.length; 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标签了)

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

   <logic:empty name="objectList">
       没有记录!!!
      </logic:empty>
   <logic:notEmpty name="objectList">
    <logic:iterate id="orderList" name="objectList">
     <tr>
      <logic:iterate id="oValue" name="orderList" property="obMap">
       <td>
        <bean:write name="oValue" property="key" />
        =
        <bean:write name="oValue" property="value" />
       </td>
      </logic:iterate>
     </tr>
    </logic:iterate>
   </logic:notEmpty>

 
评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!