select multiple new() object in hql query

夙愿已清 提交于 2019-12-12 03:47:06

问题


I have a question about hql language. I'm trying to generate DTO's via hql syntax on my WCF REST application. I have a problem with the second query. What is wrong with it? Is there any other way to reach the same result?

This works good.

session.CreateQuery(@"select new EntityTypeDTO(t.ID, t.Title, assc.ID)
                            from crmEntityType t
                          left outer join t.Association as assc").List<EntityTypeDTO>();

This does not work.

session.CreateQuery(@"select new EntityTypeDTO(t.ID, t.Title, assc.ID, new CustomFieldDTO(f.ID,f.EntityType,f.FieldType,f.Name,f.Value))
                            from crmEntityType t
                          join fetch t.Fields as f
                          left outer join t.Association as assc").List<EntityTypeDTO>();

回答1:


Well, the new Xxx(field1, field2, ...) syntax is just a convenience way for creating those DTOs in a query. It is not a fully fledged programming language and as such it most probably won't support nested new calls like your new EntityTypeDTO(..., new CustomFieldDTO(...)).

What you could do instead is select the fields into a Object[] and call the constructors yourself, e.g. like this:

List<Object[]> result = query.getResultList();

for( Object[] line : result ) {
  //this is just an example, the order depends on the field order in the select clause
  //and you'd need some casts/conversion
  new EntityTypeDTO(line[0], line[1], line[2], new CustomFieldDTO(line[3], ...));
}


来源:https://stackoverflow.com/questions/13768124/select-multiple-new-object-in-hql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!