问题
I'm using javax.persistence.criteria.CriteriaBuilder and javax.persistence.criteria.CriteriaQuery to select some entities.
I now want to select only the entities that are unique which should be specified by a certain column.
There is the method javax.persistence.criteria.CriteriaQuery#distinct which only returns unique entities.
I would rather need something like
CriteriaQuery<T> distinct(String... columnNames)
Do you know how I can bake such a distinct in my JPA CriteriaQuery
?
It seems to be possible with Hibernate.
回答1:
The following statement has no sense:
I now want to select only the entities that are unique which should be specified by a certain column.
The result sets are filtered by 'distinct' if they are 'exactly the same'. The entities are not the same if only some fields are the same.
You can make distinct clause on resultset in the following manner:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Friend> c = query.from(Friend.class);
query.multiselect(c.get(Friend_.firstName),c.get(Friend_.lastName)).distinct(true);
then you will get unique combination of firstName and lastName from Friend entities.
So for instance... 'Give me all unique combinations from my Friends where the firstName and lastName of the friend is unique.' But it doesn't mean give me unique friends.
回答2:
distinct takes a boolean as parameter. You can use multiselect to select more than one column like in this example:
CriteriaQuery<Country> q = cb.createQuery();
Root<Country> c = q.from(Country.class);
q.multiselect(c.get("currency"), c.get("countryCode")).distinct(true);
来源:https://stackoverflow.com/questions/36159151/specfiy-columns-which-should-be-considered-for-distinct-calculation