Hibernate: HQL in Depth - HQL in the Real World
(Page 3 of 4 )
Until now I was doing all the setting up and configuration in the main(). This time I will be creating a class with a reusable and (almost) generic function. The setting up of the Hibernate will happen in the constructor. So let's begin.
First, the usual: package name and imports:
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
Then the class declaration:
public class OrderOP {
:
:
}
Now comes the constructor and the configurations:
public class OrderOP {
SessionFactory sf;
public OrderOP(){
Configuration cfg = new Configuration()
.addClass(Order.class);
sf = cfg.buildSessionFactory();
}
:
:
}
The next function retrieves the data(Orders and Product) on the basis of the upper and lower priceTotals passed as arguments.
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();
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 = q.list();
Order o=(Order)list.iterator.next();
return o;
}
:
:
}
And last but not least, the main function for testing:
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();
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 = q.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
}
}
That’s it. Such a class can be used as a data processing layer’s component. In the future I will be adding more functionalities to it.
Next: Points to Remember >>
More Java Articles
More By A.P.Rajshekhar