Hebernate多表查询,结果集组装方法

1.编写连表sql,注意hql与sql的区别即可

 

 String hql = "select pi.id,pi.nam,pm.mId,pm.mversion from PM pm, PI pi where pm.id=pi.id and pm.mId =:mId";

 

2.打开查询

 

 

QueryParams q = new QueryParams();
q.addParam("mId", mId);
List result = query(hql, q);
Iterator it = result.iterator();
 public List query(final String hql, final QueryParams queryParam) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Query resultQuery = session.createQuery(hql);
				resultQuery.setCacheable(cacheable);
				resultQuery = QueryParams.setParams(resultQuery, queryParam);

				List reval = resultQuery.list();
				return reval;
			}
		});
	}

 3.装配查询结果

 

List<DemoBean> beans = new ArrayList<DemoBean>();
while (it.hasNext()) {
	DemoBean bean = new DemoBean();
	Object[] tuple = (Object[]) it.next();
	bean.setId((Integer)tuple[0]);
	bean.setName((String)tuple[1]);
	bean.setMId((Integer)tuple[2]);
	bean.setMversion((String)tuple[3]);
	beans.add(bean);
}
 

这样整个查询就完成了,简单方便。

 

你可能感兴趣的:(Hibernate)