My new website on Artificial Intelligence and Machine Learning www.aimlfront.com

Hibernate Query Language(HQL)

Querying in Hibernate

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.
Although you can use SQL statements directly with Hibernate using Native SQL but I would recommend to use HQL whenever possible to avoid database portability hassles, and to take advantage of Hibernate's SQL generation and caching strategies.
1) Executing Queries :
Query: session.createQuery(String queryString)
Create a new instance of Query for the given HQL query string.
String hql = "select * from PARENT"
Query query = session.createQuery(hql);
List list    = query.list();

String hql = "select * from PARENT parent where parent.name like 'S%'"
Cat cat=session.createQuery(hql).list().uniqueResults();

2) Filtering collections:
Query: session.createFilter(Object collection, String queryString)
Create a new instance of Query for the given collection and filter string.
Collection<Child> childs = parent.getChilds();
Query query = session.createFilter(childs," where this.name like 'S%'");
List list = query.list();

3) Criteria Queries:
Criteria:session.createCriteria(Class persistentClass)
Create a new Criteria instance, for the given entity class, or a super class of an entity class.

Criteria criteria=session.createCriteria(Parent.class);
criteria.add(Restrictions.like("name","S%");
List list=criteria.list();

4) Queries in native SQL:
SQLQuery: session.createSQLQuery(String queryString)
Create a new instance of SQLQuery for the given SQL query string.
String sqlString="SELECT * FROM PARENT where name like 'S%'";
SQLQuery sqlQuery=session.createSQLQuery(sqlString);
List list= sqlQuery.list();

5) Modifying persistent Object:
void: session.update(Object object)
Update the persistent instance with the identifier of the given detached instance.
void: session.save(Object object)
Persist the given transient instance, first assigning a generated identifier.
Object: session.load(Class theClass, Serializable id)
Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.
void: session.delete(Object object)
Remove a persistent instance from the data store
In this approach, we should form object based on operation we should call appro[riate method to perform action on DB.

Object:
	Parent parent=new Parent();
	parent.setId(123);
	parent.setName("Rani");
	parent.setChildren(childList);

	INSERT:   session.save(parent);

	DELETE:   session.delete(parent);

	UPDATE:   session.update(parent);

	SELECT:   session.load(parent);

NOTE: session.commit() After calling commit, then only data will be updated in database.