rozerro
rozerro

Reputation: 7156

Criteria API and unique results

The next code results with all rows where ispassed=true:

Criteria crit = hSession.createCriteria(ResultTable.class);
crit.add( Restrictions.eq("ispassed", true));
crit.setProjection(Projections.rowCount());
total = (long) crit.uniqueResult();

But 'ResultTable' table contains also user_id column and there can be rows like:

-ispassed              -user_id
true                    1
true                    1
true                    2
true                    3
true                    4

So how can I get only rows where user_id is unique? So that the result must be 4.

Upvotes: 0

Views: 340

Answers (2)

I think you wanted to get the number of rows whose isPassed status is true and want to consider only one such record per user. If so, you can try:

Criteria crit = hSession.createCriteria(ResultTable.class);
crit.add( Restrictions.eq("ispassed", true));
crit.setProjection(Projections.groupProperty("userId"));
total = crit.list().size();

NOTE: Assuming user_id is mapped as userId field in your ResultTable entity.

Upvotes: 1

osoblanco
osoblanco

Reputation: 498

Projections.distinct() should get only distinct combinations.

Look here for some examples: How to add Distinct in Hibernate Criteria

Upvotes: 0

Related Questions