休眠,使用不重复且内部计数超过一列

时间:2018-08-08 12:52:15

标签: java sql hibernate jpa hql

如何将下面显示的SQL查询重写为HQL?我想使用javax.persistence.Query

SELECT COUNT(DISTINCT(book_id, author_id)) FROM dbo.book bo LEFT JOIN dbo.author au ON au.id = bo.author_id LEFT JOIN dbo.publisher pu ON pu.id = bo.publisher_id WHERE pu.id = 777

我的尝试无效:

SELECT COUNT(DISTINCT(bl.id, o.id)) FROM PRDAuthor as o LEFT JOIN FETCH o.bookList as bl WHERE bl.publisher.id = 777

编辑:我要附加我的实体

PRDAuthor

public class PRDAuthor {

    // ...
    @OneToMany(orphanRemoval = true, mappedBy = "author", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    @BatchSize(size = 100)
    private List<PRDBook> bookList = new ArrayList<>();
    // ...
}

PRDBook

public class PRDBook {

    // ...
    @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @BatchSize(size = 30)
    private PRDAuthor author;

    @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @BatchSize(size = 30)
    private PRDPublisher publisher;

    // ...
}

PRDPublisher

public class PRDPublisher {

    // ...
    @OneToMany(orphanRemoval = true, mappedBy = "publisher", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    @BatchSize(size = 100)
    private List<PRDBook> bookList = new ArrayList<>();
    // ...
}

1 个答案:

答案 0 :(得分:1)

您只能按一个字段进行计数 试试这个(未测试):

SELECT COUNT(DISTINCT(*)) FROM PRDAuthor as o 
LEFT JOIN FETCH o.bookList as bl
WHERE bl.publisher.id = 777