ne1s
ne1s

Reputation: 101

Hibernate Native SQLQuery extract values

How can I extract multiple values from native SQLQuery?

SQLQuery query = session.createSQLQuery("SELECT param1, param2 from table_name where ..);

When I use query.list() or query.uniqueResult, it returns always list of Object\Object, which cannot be cast to anything even if I add scalars. No problems on extraction single value:

session.createSQLQuery("SELECT param1 from table_name where ..);
Long result = (Long)query.uniqueResult();

But how can I extract 2 or more values ?

Upvotes: 2

Views: 2326

Answers (1)

Beck Yang
Beck Yang

Reputation: 3024

According to SQLQuery.list() API:

Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[]

Sample code:

SQLQuery query = session.createSQLQuery("SELECT param1, param2 from table_name where ..);
List<Object[]> list = (List<Object[]>)query.list();//Object[] objs = (Object[])query.uniqueResult()
for (Iterator<Object[]> iterator = list.iterator(); iterator.hasNext();) {
    Object[] e = iterator.next();
    String param1 = (String)e[0];//case object type to another by youself...
}

If your program add scalar to SQLQuery, Hibernate could return match object type as you expected.

Upvotes: 1

Related Questions