Java Reference
In-Depth Information
Criteria crit = session.createCriteria(Supplier.class);
Criteria prdCrit = crit.createCriteria("products");
prdCrit.add(Restrictions.gt("price",new Double(25.0)));
List results = crit.list();
Going the other way, we obtain all the products from the supplier MegaInc using many-
to-one associations:
Criteria crit = session.createCriteria(Product.class);
Criteria suppCrit = crit.createCriteria("supplier");
suppCrit.add(Restrictions.eq("name","MegaInc"));
List results = crit.list();
Although we can use either Criteria object to obtain the results, it makes a difference
which criteria we use for ordering the results. In the following example, we are ordering the
supplier results by the supplier names:
Criteria crit = session.createCriteria(Supplier.class);
Criteria prdCrit = crit.createCriteria("products");
prdCrit.add(Restrictions.gt("price",new Double(25.0)));
crit.addOrder(Order.desc("name"));
List results = prdCrit.list();
If we wanted to sort the suppliers by the descending price of their products, we would use
the following line of code. This code would have to replace the previous addOrder() call on the
supplier Criteria object.
prdCrit.addOrder(Order.desc("price"));
Although the products are not in the result set, SQL still allows you to order by those results.
If you get mixed up with which Criteria object you are using and pass the wrong property name
for the sort-by order, Hibernate will throw an exception.
Distinct Results
If you would like to work with distinct results from a criteria query, Hibernate provides
a result transformer for distinct entities, org.hibernate.transform.
DistinctRootEntityResultTransformer , which ensures that no duplicates will be in your
query's result set. Rather than using SELECT DISTINCT with SQL, the distinct result transformer
compares each of your results using their default hashCode() methods, and only adds those
results with unique hash codes to your result set. This may or may not be the result you would
expect from an otherwise equivalent SQL DISTINCT query, so be careful with this. An additional
performance note: the comparison is done in Hibernate's Java code, not at the database, so
non-unique results will still be transported across the network.
Projections and Aggregates
Instead of working with objects from the result set, you can treat the results from the result set
as a set of rows and columns. This is similar to how you would use data from a SELECT query
with JDBC; also, Hibernate supports properties, aggregate functions, and the GROUP BY clause.
Search WWH ::




Custom Search