Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specfiy columns which should be considered for distinct calculation

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.

like image 615
Harold L. Brown Avatar asked Mar 22 '16 15:03

Harold L. Brown


1 Answers

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.

like image 122
Łukasz Rzeszotarski Avatar answered Sep 25 '22 21:09

Łukasz Rzeszotarski