Skip to content

Instantly share code, notes, and snippets.

@chkal
Created March 15, 2011 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chkal/870980 to your computer and use it in GitHub Desktop.
Save chkal/870980 to your computer and use it in GitHub Desktop.
Custom result objects with Criteria4JPA
public static class CountryAndQuantity {
private final String country;
private final Long quantity;
public CountryAndQuantity(String country, Long quantity) {
this.country = country;
this.quantity = quantity;
}
public String getCountry() {
return country;
}
public Long getQuantity() {
return quantity;
}
}
// Create new criteria
Criteria criteria = CriteriaUtils.createCriteria( entityManager, Person.class );
// Add constructor projection
criteria.setProjection( Projections.constructor( CountryAndQuantity.class )
.add( Projections.relativeGroupPath("country") )
.add( Projections.count("id") )
);
// Execute the query
List<CountryAndQuantity> result = criteria.getResultList();
// Display result
for( CountryAndQuantity row : result ) {
log.info( "There are " + row.getQuantity() + " people from " + row.getCountry() );
}
There are 8 people from US
There are 3 people from Germany
There are 2 people from France
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment