1.11.2009

Hibernate Criteria API and Projections

1. Group by

ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("companyname"));
proList.add(Projections.count("companyname"));
proList.add(Projections.groupProperty("companyname"));

Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(proList);

List groupedCompanyNames = criteria.list();

Output :


image


2. Distinct




ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("companyname")));
Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(proList);

List distinctdCompanyNames = criteria.list();







Output:

image


3. setResultTransformer




ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("companyname")));
proList.add(Projections.count("companyname"));
proList.add(Projections.groupProperty("companyname"));
Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(proList);

List<Customers> customerList = criteria
.setResultTransformer(new AliasToBeanResultTransformer(Customers.class)).list();

4. where in = subqueries



DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Orders.class);
detachedCriteria.setProjection(Projections.distinct(Property.forName(("customers"))));

ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("companyname")));
proList.add(Projections.property("customerid"));
proList.add(Projections.count("companyname"));
proList.add(Projections.groupProperty("companyname"));
proList.add(Projections.groupProperty("customerid"));
Criteria criteria = session.createCriteria(Customers.class);


criteria.add(Property.forName("customerid").in(detachedCriteria));
criteria.setProjection(proList);


List<Customers> customerList = criteria
.setResultTransformer(new AliasToBeanResultTransformer(Customers.class)).list();



image



Technorati Tags: ,,

Hiç yorum yok: