Friday, July 17, 2015

HQL (Hibernate Query Language) – FROM Clause

Hibernate Provides a very good Query Language HQL (Hibernate Query Language) in the form of OOPs. Hibernate is very much similar to the SQL but it follow the OOPs strictly so you have to be very carefull about it. So we will start with few basic example to understand how to write the HQL Queries.
FROM Clause (SELECT Query)
SQL : – select * from person
HQL : – 1. from com.hibernate.enity.Person
           2. from com.hibernate.enity.Person p
           3. select p from com.hibernate.enity.Person p
All the above three HQL queries will result the same output. So you can say the SQL query(select * from person) is similar to all the above three HQL queries.Now we will take each keyword from Hibernate query and will try to understand
1. from com.hibernate.enity.Person
from : – It is a keyword just similar to SQL query
com.hibernate.enity.Person : – You have to specify the complete package name along with the class name.(* package name should be the exact and Class name first letter should be capital)
2. from com.hibernate.enity.Person p
from : – It is a keyword just similar to SQL query
com.hibernate.enity.Person p : – Here p is an alias which we have created for the class Person rest of the details are same as explained above
3. select p from com.hibernate.enity.Person p
After reading the above points 1,2 this query will be self explanatory for you.
Please follow the code sample below : -
1.Project Structure

2. FROM clause code
/* Hibernate select query Example */
    public void selectFromTable(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        //begin the transaction
        Transaction trans=session.beginTransaction();
        //select query example
        String selectQuery = "select p from com.hibernate.enity.Person p";
        Query query = session.createQuery(selectQuery);
        //select query will return multiple result set.
        //create a list : -List personList and cast the output to store into the personList
        List personList = (List)query.list();
        //print the results for the personList
        for(Person personObj:personList){
            System.out.println("Id : -  "+personObj.getId()+" First Name : - "+personObj.getFirstName()+" Last Name : - "+personObj.getLastName());
MYSQL data records of person table  

No comments:

Post a Comment