我正在使用JPQL,希望在一个构造表达式中接收一些普通参数和一个集合,以直接创建DTO对象。但如果集合是空的,我总是会得到一个错误,因为它找不到正确的构造函数:
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();
目前的问题是,如果p.childs为空,它会提示找不到正确的构造函数,需要的是(long, String, Child)而不是(long, String, Collection)。
你有任何解决方案吗?或者在构造函数表达式中使用Collection根本不可能吗?
还有一件事:如果我轻松创建两个构造函数(..., Collection childs AND ..., Child childs),我既没有结果,也没有错误... 在我看来并不是很令人满意 :-/