【发布时间】:2011-08-25 07:11:34
【问题描述】:
我正在使用 JPQL,并希望在构造函数表达式中接收一些普通参数和一个集合,以直接创建 DTO 对象。但是如果Collection是空的,我总是会报错,因为他没有找到正确的构造函数:
DTO 类如下所示:
public class DTO {
private long id;
private String name;
private Collection<Child> children;
public DTO (long id, String name, Collection<Child> children){
this.id = id;
this.name = name;
this.children= children;
}
}
子类:
public class Child {
private String name;
private int age;
}
现在构造函数表达式如下所示:
return (List<DTO>) getEm().createQuery("SELECT DISTINCT NEW de.DTO(p.id, p.name, p.childs)
FROM Parent p").getResultList();
当前的问题是,如果 Collection p.childs 为空,它说它没有找到正确的构造函数,它需要 (long, String, Child) 而不是 (long, String, Collection)。
您有任何解决方案,还是根本不可能在构造函数表达式中使用集合?
还有一件事:如果我轻松地创建两个构造函数(...、Collection childs AND ...、Child childs),我不会得到任何结果,但也没有错误...在我看来并不是很满意:- /
【问题讨论】:
-
我认为您忘记发布您的
Parent课程。child的复数形式也是children。 -
您是否尝试过在查询中添加条件 - "WHERE p.childs IS NOT EMPTY AND SIZE(p.childs) 0"
-
我也在寻找类似的东西,我能找到的最接近你所问的东西(不依赖额外的库)是@VladMihalcea 的标题为How to fetch a one-to-many DTO projection with JPA and Hibernate 的帖子 -这是我对Q46681780 的评论的副本,因为它看起来非常接近这个评论。如果这被视为垃圾邮件或其他内容,我们深表歉意......
标签: java jpa constructor expression jpql