Hibernate Query Language (HQL) SELECT Clause
In this section, you will learn about hibernate query language (HQL) SELECT clause. Hibernate SELECT clause provides you get result from tables. And you get specific field from table.
Here you will the hibernte query to select records according to java object bean properties.
Following example you see "SELECT em.empName,em.empSal FROM Employee AS em" means you get only two fields from employee table.
You will see the following running example to use hibernate query language (HQL) SELECT Clause.
package developerhelpway.hibernate.hql;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import developerhelpway.hibernate.Employee;
public class SelectClauseExample {
/**
* @param args
*/
public static void main(String[] args) {
Session sess = null;
try{
SessionFactory sf = new Configuration().
configure().buildSessionFactory();
sess = sf.openSession();
String hql = "SELECT em.empName, em.empSal
FROM Employee AS em";
Query query = sess.createQuery(hql);
Object[] employees = query.list().toArray();
for(Object employee: employees){
Object[] emp = (Object[]) employee;
System.out.println(
"EmpName: " + emp[0].toString()
+ ", EmpSal: " + Double.valueOf(emp[1].toString())
);
}
Transaction tr = sess.beginTransaction();
tr.commit();
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(sess != null){
sess.close();
}
}
}
}
|
Download Code:
employee table:

OutPut:
