Three ways to create query in Hibernate

Create Query in Hibernate

To create query in the Hibernate ORM framework, there is three different types. The following are the
three ways to create query instance:

  1. session.createQuery()
  2. session.createSQLQuery()
  3. session.createCriteria()

We will look into the details of each category in detail.

also read:

session.createQuery()

The method createQuery() creates Query object using the HQL syntax. Fro example

Query query = session.createQuery("from Student s where s.name 
              like 'k%'");

session.createSQLQuery()

The method createSQLQuery() creates Query object using the native SQL syntax. Fro example

Query query = session.createSQLQuery("Select * from Student");

session.createCriteria()

The method createCriteria() creates Criteria object for setting the query parameters.
This is more useful feature for those who don’t want to write the query in hand. You can specify any type of complicated syntax using the Criteria API.

Criteria criteria = session.createCriteria(Student.class);

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. In the 2nd example shouldn't it be
    Query query = session.createSQLQuery("Select * from Student");
    instead
    Query query = session.createQuery("Select * from Student");

  2. suthukrish says:

    HI,

    Basically createSQLQuery and createQuery methods are two different methods. When you are using the createSQLQuery() method, you have to pass native sql query. you cannot pass HQL query. This article explains the three different ways to create the queries using the hibernate. Sometime you want to create the native SQL query to execute, that time you have to use createSQLQuery().

    If you want to use the HQL (Hibernate Query), then go for the createQuery() method.

  3. your example still has the error!

  4. As mentioned a few times before, there’s an error in your second example. You’re making a native SQL query using createQuery(), though it SHOULD be createSQLQuery(). createQuery() can only be used with HQL right? So this would be incorrect:
    Query query = session.createQuery(“Select * from Student”);
    Which is what you have in your second example.

    Thanks for the article. It has been helpful.

    • I think I and others would benefit from this article having this error fixed. If someone can edit it, we’d all appreciate it.

      • krishnas says:

        Thank you for pointing the mistake. I have updated with the correct syntax.

        Thanks,
        Krishna

  5. you can find some more details in the below link,”http://javadomain.in/hibernate-select-query-example-in-java/”

Speak Your Mind

*