Greg
Greg

Reputation: 1389

JPA Criteria Query distinct

I am trying to write a distinct criteria query, using:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<RuleVar> query = builder.createQuery(RuleVar.class);
Root<RuleVar> ruleVariableRoot = query.from(RuleVar.class);
query.select(ruleVariableRoot.get("foo").<String>get("foo")).distinct(true);

Based on the example in the javadoc for CriteriaQuery.select()

CriteriaQuery<String> q = cb.createQuery(String.class);
 Root<Order> order = q.from(Order.class);
 q.select(order.get("shippingAddress").<String>get("state"));

However, this gives me an error:

The method select(Selection<? extends RuleVar>) in the type CriteriaQuery<RuleVar> is not applicable for the arguments (Path<String>)

Can someone please point out what I am doing wrong? Or how to get a Selection object from a Path?

Upvotes: 32

Views: 82294

Answers (1)

Greg
Greg

Reputation: 1389

I got it. The problem was my CriteraQuery needed to be of type String. This works:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<String> query = builder.createQuery(String.class);
Root<RuleVar> ruleVariableRoot = query.from(RuleVar.class);
query.select(ruleVariableRoot.get(RuleVar_.varType)).distinct(true);

Upvotes: 76

Related Questions