I\'m using JPQL and want to receive some normal parameters and a collection in a Constructor Expression to directly create the DTO-objects. But if the Collection is empty, I
Try,
public DTO (long id, String name, Object children)
This is not an answer.
The JPA 2.0 spec doesn't, as far as i can see, allow the use of collections as parameters in constructor expressions. Section 4.8 defines a constructor expression like this:
constructor_expression ::=
NEW constructor_name ( constructor_item {, constructor_item}* )
constructor_item ::=
single_valued_path_expression |
scalar_expression |
aggregate_expression |
identification_variable
A single_valued_path_expression
is what it sounds like - a property expression that points to a scalar of some sort (such as p.id
), a scalar_expression
is also an expression that points to scalar, an aggregate_expression
is the application of a function like sum
which reduces a multi-valued expression to a scalar one, and an identification_variable
is a reference to the type you're querying over. None of which can be collection-valued. Assuming i've read the spec right.
So, if your JPA provider lets you use collection-valued parameter in a constructor expression, it's because it's going above and beyond the spec. Which is very nice of it, but not something you can necessarily rely on!
I had a similar problem and tried "Object" in DTO constructor as James suggested, but a child object is passed in and it seems that it is only the first child instead of the expected List/Array of children.
I ended up with a "normal" query creating all the DTOs in a for loop.
TypedQuery<Parent> query = em.createQuery("SELECT p FROM Parent p", Parent class);
List<Parent> list = query.getResultList();
List<DTO> result = new ArrayList<>();
for (Parent p : list)
{
DTO dto = new DTO();
//set dto props and fill collection
result.add(obj);
}
return result;