I have written two methods that executes any type of HQL and returns data. Methods are like
public static Query getHqlQueryObject(String hql) throws Exception{
Query query = null;
Session session = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction transaction = session.beginTransaction();
query = session.createQuery(hql);
} catch (Exception e) {
System.out.println("Exception in Helper::getHqlQueryObject");
e.printStackTrace();
}
return query;
}
public static List<Object> getHqlQueryData(Query query) throws Exception{
List dataList = new ArrayList();
Session session = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction transaction = session.getTransaction();
dataList = query.list();
transaction.commit();
} catch (Exception e) {
System.out.println("Exception in Helper::getHqlQueryData");
e.printStackTrace();
}
return dataList;
}
I am calling this methods like this
Query query = Helper.getHqlQueryObject("from BookDetails where pkBookId = :pkBookId");
query.setParameter("pkBookId", new Long(1));
List dataList = Helper.getHqlQueryData(query);
My question is, is it right approach? or should I write session initialization code every time when I want to execute a query?
Exception
is not a good idea. You should at least re-throw it. \$\endgroup\$ – Florent Bayle Aug 27 '14 at 9:38