1. 程式人生 > >Hibernate 關聯查詢返回組合的Bean,而不是返回Object[]

Hibernate 關聯查詢返回組合的Bean,而不是返回Object[]

目的:hibernate 多張表關聯查詢,用到了原生的sql,那麼用到SQLQuery,返回的是Object[],如果欄位太多,在後期維護上很不方便(obj[0],obj[1],,,,),為了維護方便,就改成自定義實體;程式碼如下:

StringBuffer sql = new StringBuffer();
		sql.append(" select cust.CM_Code " );
           ...(這裡放需要反回的欄位)	    

		sql.append(" from 	表1 cos ");
		sql.append(" LEFT JOIN 表2 ord ON (cos.CO_ID = ord.CO_ID) " );
		sql.append(" inner join 表3 cust on (ord.CM_ID = cust.CM_ID) " );
		sql.append(" inner join 表4 country on (ord.CT_Code_Destination = country.CT_Code) " );
		sql.append(" inner join 表5 ordattach on (ord.CO_ID = ordattach.CO_ID) " );
		sql.append(" where 1 = 1 ");
		
		
		
		//Set query parameter
		Session session = super.getSession();
		SQLQuery query = session.createSQLQuery(sql.toString());
           query.setParameter("queryOrderNo", “123456”);
               ...(這裡放欄位對應的引數)

		   query.addScalar("CM_Code",StandardBasicTypes.STRING);
                ... (這裡放返回的資料型別)		      

		   query.setResultTransformer(Transformers.aliasToBean(javaBean.class));
		//Set query return
		List<CustomerOrderForecastDTO> returnList = query.list();

簡化後的程式碼入上,僅僅作參考,需要耐心看完才能懂..