views:

339

answers:

1

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 {
  @olumn(name="NAME")
  String name;

  @ManyToMany(targetEntity= Contacts.class, fetch = FetchType.EAGER)
  @JoinTable(name="USER_DEPARTMENT_CONTACTS",
           joinColumns=@JoinColumn(name="DEPARTMENT_ID"),
           inverseJoinColumns=@JoinColumn(name="USER_ID"))
  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?

+2  A: 

Hi, 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

Arthur Ronald F D Garcia