Hibernate Query Language:
HQL provides a platform independent way of querying a database by mapping commands in HQL to the native database commands.
HQL is case insensitive except for class names.
Example:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Query query = session.createQuery("from Person p where p.friend.name = :friendName ");
query.setParameter("friendName", "John");
List list = query.list();
// Parameter-value can also be specified inline:
Query query = session.createQuery("from Person p where p.friend.name = 'John' ");
List list = query.list();
Note the use of p.friend.name. This is not possible in normal SQL.
HQL will automatically do a join for such multi-level expressions.
In fact, in the above queries, 'friend' is a field in class Person and 'name' is a field in 'friend' !
Criteria and Restrictions:
Criteria-based queries provide another abstraction layer over HQL by specifying even the query in terms of objects.
This frees the programmer from worrying about syntax details like comma, brackets, where etc.
Example:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Criteria crit = session.createCriteria (Person.class);
crit.add (Restrictions.like ("name", "John"));
crit.add (Expression.between ("age", new Integer(7), new Integer(30)));
crit.addOrder( Order.asc("age") );
// Pagination in Criteria queries
crit.setMaxResults(10);
crit.setFirstResult(20);
List persons = crit.list();
Native SQL Queries:
Hibernate also provides API to use native query language.
This comes in handy when Hibernate lacks appropriate mapping for a native language construct.
Example:
Query query = session.createSQLQuery("select * from person p where p.age = :ageValue")
.addEntity(Person.class)
.setParameter("ageValue", "25");
List result = query.list();
// If addEntity is not there, Hibernate will return an Object array.
Query query = session.createSQLQuery("select * from person p where p.age = :ageValue")
.setParameter("ageValue", "25");
List result = query.list();
Note that when using SQL instead of HQL, you cannot specify multi-level expressions like p.friend.name
Got a thought to share or found a bug in the code? We'd love to hear from you: