SELECT DISTINCT + ORDER BY in JPA 2 Criteria API

后端 未结 2 1780
渐次进展
渐次进展 2021-01-02 03:53

I\'ve a class Lawsuit, that contains a List, each one with a Date attribute.

I need to select all the Law

相关标签:
2条回答
  • 2021-01-02 04:29

    You can also de-duplicate via group by based on primary key column of root table:

     cq.groupBy(root.get("id")); // Assuming that Lawsuite.id is primary key column
    
    0 讨论(0)
  • 2021-01-02 04:52

    I've discovered the source of the problem somewhere else, and solving it has made unnecessary to do what asked in the question; as described in other answers, it should be unnecessary to perform the distinct here.

    The duplicate rows were originated by erroneous left joins that were performed on collections (attributes of the root object) even if the predicates were not been used:

    Join<Lawsuit, Witness> witnesses = root.join("witnesses", JoinType.LEFT);
    if (witnessToFilterWith!=null) {
        predicateList.add(cb.equal(witnesses.<Long>get("id"),witnessToFilterWith.getId()));
    }
    

    The join should obviously be performed as inner and only if needed:

    if (witnessToFilterWith!=null) {
        Join<Lawsuit, Witness> witnesses = root.join("witnesses", JoinType.INNER);
        predicateList.add(cb.equal(witnesses.<Long>get("id"),witnessToFilterWith.getId()));
    }
    

    So, if you're here because you're getting the same problem, search the problem in the joins.

    0 讨论(0)
提交回复
热议问题