Hibernate - Traversing createSQLQuery results and reading into appropriate object
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
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();
}
}
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]);
for a better solution, try to use ResultTransformer
you can find more about ResultTransformer in Hibernate Docs.
精彩评论