Reputation: 3479
Why I have to use Object[]
to print the list if I select specific columns:
Session session = DaoSF.getSessionFactory().openSession();
List<Object[]> list = new ArrayList<Object[]>(); /* Object[] */
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"group by test.col1, test.col2, test.col3");
list = criteria.list();
for (Object[] item : list)
{
System.out.println(item[1] + ", " + item[2] + ", " + item[3]);
}
And why is it possible to iterate the same select (select * -- not the specific columns) using original Test object?
List<Test> list = new ArrayList<Test>(); /* Test */
Query criteria = session.createQuery(
"from Test test " +
"group by test.col1, test.col2, test.col3");
list = criteria.list();
for (Test item : list)
{
System.out.println(item.getCol1 + ", " + item.getCol2 + ", " + item.getCol3);
}
Is it possible to "convert" Object[]
to Test
object?
Upvotes: 1
Views: 188
Reputation: 4210
in your first query , you return a row (like a list) , consisting of several attributes of a "test" object that you have selected.
it is not "test" object , so you cannot iterate such way.
in your second query , you return the "test" object : a list of "Test" objects , so you can iterate as "test" object.
Upvotes: 1
Reputation: 10049
Try this approach; first create a constructor in your Test
class:
public Test(Col1Type col1, Col2Type2 col2, Col3Type col3) {
this.col1 = col1;
this.col2 = col2;
this.col3 = col3;
}
Now in the query, you can say:
select new Test(t.col1, t.col2, t.col3)
from Test t
This will give Hibernate a so-called row-mapper constructor out of which it can construct the objects of Test
. Then you will have a List<Test>
from query.list()
. This approach has a catch that you should provide different constructors beside the default one for different possible queries.
Upvotes: 1