1. 程式人生 > >Hibernate 查詢結果集轉成自定義模型類class

Hibernate 查詢結果集轉成自定義模型類class

     這個問題網上的寫的粗糙,或者是問題答案不是本人想要的,這裡給出簡潔回答,大家都能看懂。

     log.debug("finding all Tbsensor instances");

     try {         

           StringBuffer queryString= new StringBuffer();

              queryString.append("select model.ID,model.TID,model.Number,monitoritem.MonitorName 

                                               from tbsensor model,tbmonitoritem  monitoritem ");

              queryString.append("where  model.MonitorID=monitoritem.ID");

           Query  queryObject = getSession().createSQLQuery(queryString);

              queryObject.setFirstResult(offset);//頁碼

              queryObject.setMaxResults(limit);//頁面大小

             queryObject.setResultTransformer(Transformers.aliasToBean(Customtbsensor.class));}//這裡的Custom

tbsensor就是自定義的類,可以轉成你想要的型別(注意:select查出的屬性要跟自定義類的屬性要完全一致,否則可能出現你意想不到的錯。)。

      catch (RuntimeException re

             {

                log.error("find all failed", re);

                throw re;

              }