Friday, March 5, 2010

Ways to fetch values using Hibernate

There are 3 ways to fetch values using Hibernate.
1) Using the HQL : just write the query in hql and map the tables to Classes and also the columns to attributes in the Class.
Ex:
String queryString = "select columName from tableX where columName like '%"+name+"%'";
List str = getHibernateTemplate().find(queryString);
Note : here in hql we are supposed to use the table attributes as column name and class names as table name.

2) Fetch directly with out using the query statement at all.
Ex : this.getSession().createCriteria(XXX.class).list();

3) write the query in the hbm.xml file and call the query from java file.
Ex :
In the java file :
getHibernateTemplate().findByNamedQuery("selectAllLike", x.trim());
In the hbm file define the selectAllLike query statement like

sql-query name="selectAllLike"
return alias="component" class="com.bofa.osm.hibernate.Component"
SELECT * FROM COMPONENT c WHERE upper(c.NAME) LIKE upper(?)
sql-query

Note : sql-query ans return are the tags.
Cheers
DeepthiMahesh

No comments: