问题
I have requirement where in I would like to create a new object within HQL query. And one of the parameters to be provided in the new Object constructor is a list of some other objects.
eg:
SELECT new Object1(a.id, new List(SELECT b FROM table2 AS b WHERE b.id>0)) FROM table1 AS a;
So I would be getting an object of type Object1 which has a list retrieved from another table.
Please do help out..
回答1:
You can't do it in one statement as you plan to. Think in a different way. There are some possibilities.
You create the mapping for Object1 to the table1 and Object2 to table2. In the mapping of Object1 you create a one-to-many relation to Object2, and this relation contains the where condition
"WHERE Object2.id>0"
from your select. Then you only need the HQL statement"from Object1"
.
This is the nicest and most hibernate-style possibility, but it only works if the where condition always is the same. And then you need a database relation between table1 and table2 (which you don't have in your example, but which probably exists and you only forgot it in your example).
orYou only load table1 first
SELECT new Object1(a.id) FROM Table1 a
and then in a loop over all elements of this list you load the second tableFROM table2 b WHERE b.id>0
and put it into the element of type Object1.
orYou only load table1 first
SELECT new Object1(a.id) FROM Table1 a
and in Object1 you have a methodgetObject2List()
which at the first call loads the list of elements from table2.
来源:https://stackoverflow.com/questions/12379238/hql-new-list-within-new-object