小编Flo*_*ian的帖子

JPQL:在构造函数表达式中接收集合

我正在使用JPQL并希望在Constructor Expression中接收一些常规参数和集合以直接创建DTO对象.但是如果Collection是空的,我总是会收到错误,因为他找不到合适的构造函数:

DTO-Class看起来如下:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

儿童班:

public class Child {
    private String name;
    private int age;
}
Run Code Online (Sandbox Code Playgroud)

现在,Constructor Expression看起来如下:

return (List<DTO>) getEm().createQuery("SELECT DISTINCT NEW de.DTO(p.id, p.name, p.childs) 
                                          FROM Parent p").getResultList();
Run Code Online (Sandbox Code Playgroud)

当前的问题是,如果Collection p.childs为空,它表示它找不到正确的构造函数,它需要(long,String,Child)而不是(long,String,Collection).

您是否有任何解决方案,或者根本无法在构造函数表达式中使用Collection?

哦还有一件事:如果我轻松创建两个构造函数(...,Collection childs AND ...,Child childs)我没有得到任何结果,但也没有错误......在我看来并不是很满意: - /

java constructor expression jpa jpql

14
推荐指数
1
解决办法
5101
查看次数

标签 统计

constructor ×1

expression ×1

java ×1

jpa ×1

jpql ×1