Today, we are going to discuss about hibernate query language which is a extremely powerful language.
HQL (Hibernate Query Language)
Hibernate Query Language or HQL is a extremely powerful language which is very similar to SQL. You may perform database operations easily using this language. It automatically generates the corresponding sql query on execution. The main thing is that this language uses Java Classes instead of table and properties instead of columns.
We show this with help of example.
First we assume that we have the below table with records.
Course table
1 | 12 | J2EE |
2 | 6 | Hibernate |
Now we will explain this:
Listing 1: Course class
package model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * * @author Anurag */ @Entity public class Course implements Serializable { @Id @GeneratedValue @Column(name = "C_ID") private Long id; private String name; private int duration; public Course() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Course(String n, int dur) { name = n; duration = dur; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
- We defined a class Course with fields like id, name, duration.
- We define the setter and getter function for these.
- We set the id to be auto generated and also we set the name for this column to be C_ID.
Now we define the configuration file.
Listing 2: hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateArt</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">csanurag</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.current_session_context_class">thread</property> <mapping class="model.Course"/> </session-factory> </hibernate-configuration>
- We defined the configuration parameter for the database.
- We also defined the mapping class for both the classes.
Now we define the Utility class which will be used to obtain instance of session factory.
Listing 3: Utility class
package Main; /** * * @author Anurag */ import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class Utility { private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Lastly we make a class which will make this all work:
Listing 4: App2 class (From clause)
package Main; /** * * @author Anurag */ import java.util.Iterator; import model.Course; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class App2 { public static void main(String args[]) { SessionFactory sf = Utility.getSessionFactory(); Session s = sf.getCurrentSession(); Transaction tx = s.beginTransaction(); //Use of from in HQL String SQL_QUERY ="from Course course"; Query query = s.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Course course=(Course)it.next(); System.out.println("Course Name: " + course.getName()); } tx.commit(); } }
- from clause can be used to retrieve the records within the table.
- We use” from <Class Name> <Any name>
- We create a query using the above.
- Now we iterate over result and display course name one by one.
Listing 5: App2 class (Select clause)
package Main; /** * * @author Anurag */ import java.util.Iterator; import model.Course; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class App2 { public static void main(String args[]) { SessionFactory sf = Utility.getSessionFactory(); Session s = sf.getCurrentSession(); Transaction tx = s.beginTransaction(); //Use of select in HQL String SQL_QUERY ="select course.id from Course course"; Query query = s.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Long id=(Long)it.next(); System.out.println("Id: " + id); } tx.commit(); } }
- First, we want to display all course id only and no other fields are needed. In this situation we need to use select.
- We create a query using select as shown above.
- We go through result of query and while iterating through each result we display it on screen.
Listing 6: App2 class (Where clause)
package Main; /** * * @author Anurag */ import java.util.Iterator; import model.Course; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class App2 { public static void main(String args[]) { SessionFactory sf = Utility.getSessionFactory(); Session s = sf.getCurrentSession(); Transaction tx = s.beginTransaction(); //Use of where in HQL String SQL_QUERY ="from Course course where id=1"; Query query = s.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Course course=(Course)it.next(); System.out.println("Course Name: " + course.getName()); } tx.commit(); } }
- where clause can be used to retrieve limited records within the table.
- Here we used the where clause to obtain records where id is 1.
- We create a query using the above.
- Now we iterate over result and display course id.
This is all for today article. See you next time with more exciting article.