Take the 2-minute tour ×

I would like to write a hql query using a dynamic instantiation with a list as one of it's parameters.

Simplified example:

A HQL query with a dynamic instantiation:

select new x.y.UserDto(u.name, u.contacts) from User u where u.xyz=:param1 ...

and my dto class constructor is:

public class UserDto {
   private String name;
   private List contacts;

   public UserDto(String name, List contacts) {
      this.name = name;
      this.contacts = contacts;

And the entity mapping:

public class User {
  String name;

  @ManyToMany(targetEntity= Contacts.class, fetch = FetchType.EAGER)
  private List<Contacts> contacts;


So as you can see all I want is to create a new object that has some properties and collections of an entity.

I can understand that Hibernate would need one or more queries to achieve this as this would generate multiple result rows for each entity.

Does anyone knows if it is possible to create a new object which is a combination of properties and collections?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Sorry but it is not possible. According to JPA specification,

The type of the query result specified by the SELECT clause of a query is AN ENTITY abstract schema type, A STATE-FIELD type - NOT A COLLECTION -, the result of an aggregate function, the result of a construction operation, OR SOME SEQUENCE OF THESE.

You could use the following instead:

select DISTINCT new x.y.UserDto(u) from User u LEFT JOIN FETCH u.contacts

So, this way you would have the users with your contacts fetched

share|improve this answer
add comment

Your Answer


