Search code examples
javamysqlsqlhibernatehql

Hibernate equivalent of getTimestamp() and getInt()


I am currently using ResultSet but want to switch over to Hibernate queries.

I have this code:

Statement stmt = nfCon.createStatement();
stmt = nfCon.createStatement();
ResultSet foo = stmt.executeQuery(sql);

String str = " " + foo.getTimestamp("time").getTime()  + ", " + foo.getInt("len");

How can I change it if I am using

Query query = session.createQuery(hql);
List<String> list = query.list(); 

Obviously, I can't do list.getTimestamp("time");. My SQL/HQL is a select statement. Any help would be appreciated!


Solution

  • select xxx as time, yyy as len from zzz where ...
    
    List<Object[]> list = query.list(); 
    
    for (Object[] row : list) {
       Date date = (Date) row[0];
       int len = ((Number) row[1]).intValue();
       String str = " " + date.getTime()  + ", " + len;
    }
    

    This is a general solution. If len is a mapped integer field of an entity, then you can cast it directly to int (or better Integer, especially if it is nullable).

    You might also want to look at constructor invocation from HQL, as it could help reduce the boilerplate code involved when representing projected columns as Object arrays.