Hibernate: Criteria Queries in Depth - A Criteria Query in the Real World
(Page 4 of 4 )
Now it is time to apply what we have discussed up till now. In this section I will be rewriting the application developed in the previous article (HQL in Depth). Almost all the code is same except the query part. So the details are as below:
package com.someorg.persist.op;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.someorg.persist.Order
import org.hibernate.*;
import org.hibernate.criterion.*;
public class OrderOP {
SessionFactory sf;
public OrderOP(){
Configuration cfg = new Configuration()
.addClass(Order.class);
sf = cfg.buildSessionFactory();
}
public Order getOrder(String lower, String upper){
// open session
Session sess = sf.openSession();
//The following code has been commented so that
//comparison between HQL and Criteria Query
/*String query = "select o from o "
+ "Order as o join o.products as p "
+ "where o.priceTotal > :priceTotalLower "
+ "and o.priceTotal < :priceTotalUpper";
Query q = sess.createQuery(query);
q.setDouble("priceTotalLower",
Double.parseDouble(lower));
q.setDouble("priceTotalUpper",
Double.parseDouble(upper));
*/
List list = sess.createCriteria(Order.class)
.add(Restrictions.between(lower,upper)
. list();
Order o=(Order)list.iterator.next();
return o;
}
public static void main(String args[]){
Order o=OrderOP().getOrder(“2000’,”3000”);
System.out.println(“Order Id:”+ o.id);
//and so on
}
}
You can see from the above code that if the object-oriented approach is really clear, then Criteria APIs are the easiest mode of data retrieval. That brings us to the end of this discussion. However, Hibernate is not just about CRUD operations. It is also about transaction and entity management as well as optimization techniques. These are topics that will be covered in the future.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |