Specfiy columns which should be considered for distinct calculation

孤街醉人 提交于 2021-02-18 12:18:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!