Make delicious recipes!


Querying in Hibernate


Querying in Hibernate can be done in three ways:
  1. 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' !





  2. 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();
    
    
    Expression class has been deprecated. Always use Restrictions



  3. 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






Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal