java Hibernate - 遍历 createSQLQuery 结果并读入适当的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3504627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:08:48  来源:igfitidea点击:

Hibernate - Traversing createSQLQuery results and reading into appropriate object

javahibernate

提问by IamBanksy

I am pretty new to Hibernate / Java (JSF 2.0) and I am attempting to call a custom query and read the results into an object that I have created Logins. Logins has two setter functions, setLoginDate(Date date) and setUserId(Integer userId) my function looks like so, The issue I am having is how to transform the result set and read in the appropriate values into a temp loginList

我是 Hibernate / Java (JSF 2.0) 的新手,我正在尝试调用自定义查询并将结果读入我创建的登录对象中。Logins 有两个 setter 函数, setLoginDate(Date date) 和 setUserId(Integer userId) 我的函数看起来像这样,我遇到的问题是如何转换结果集并将适当的值读入临时登录列表

public List<Logins> getUserLogins() {

     Session session = getSessionFactory().openSession();
     List<Logins> loginList = null;
     Login temp = null;

     try {

         String SQL_QUERY = "SELECT login_date, user_id FROM user_logins";
         Query query = session.createSQLQuery(SQL_QUERY);

         List results = query.list();
         for(ListIterator iter = results.listIterator(); iter.hasNext(); ) {

              ** THIS IS THE PART I AM NOT CLEAR ON ***
              temp.setLoginDate(resutls.get(0));
              temp.setUserId(results.get(1));

              loginList.add(temp);
              temp = null;

              *****************************************

              return loginList;
         }

     } catch(HibernateException e) {
         throw new PersistanceDaoException(e);
     } finally {
         session.close();
     }

}

回答by mhshams

missing part:

遗失的部分:

      Object[] row = (Object[]) iter.next();
      temp = new Login();
      temp.setLoginDate(row[0]);
      temp.setUserId(row[1]);

you may need to cast row[i]to your target object for example if login date is a date object: temp.setLoginDate((Date) row[0]);

row[i]例如,如果登录日期是日期对象,则您可能需要强制转换为目标对象:temp.setLoginDate((Date) row[0]);

回答by mhshams

for a better solution, try to use ResultTransformeryou can find more about ResultTransformer in Hibernate Docs.

要获得更好的解决方案,请尝试使用ResultTransformer您可以在 Hibernate Docs 中找到有关 ResultTransformer 的更多信息。