Hi All,
I am Jyoti Ranjna working as a software engineer This blog is about the use of constructor in HQL.
Need of Constructor in HQL
Well when we use hql statement that will select all the attributes from the POJO class, no problem to type cast the retuen type to corresponding POJO Class reference. As below example shows:
List list = session.createQuery("from Contact c ").list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Contact contact = (Contact) iterator.next();
System.out.print("First Name ==>> " + contact.getFirstName());
System.out.println("Last Name ==>> " + contact.getLastName());
}
This time the "list" contain object of type Contact. So no problem in type casting it to Contact class (pojo) reference. But what will happened if we select specified attributes like below:
List list = session.createQuery("select c.firstName, c.lastName from Contact c ").list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Contact contact = (Contact) iterator.next();
System.out.print("First Name ==>> " + contact.getFirstName());
System.out.println(" Last Name ==>> " + contact.getLastName());
}
This time it will through a java.lang.ClassCastException. Beacuse this time the list contains type Object. So it is not possible to type cast to POJO class reference.
But in some cases we required pojo class object. At that time constructor will be usefull in HQL statements. Create a constructor using those attributes which you required in select statements. Like below:
Contact.java
package jyoti.ssis.hibernate;
/** * @author Jyoti Ranjna * * http://www.softidsolutions.com/
* Java Class to map to the datbase Contact Table
*/
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
/* Default Constructor
* */
public Contact() {
}
/** required parametrized constructor
* @param firstName
* @param lastName
*/
public Contact(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
/** * @return Email
*/
public String getEmail() {
return email;
}
/** * @return First Name
*/
public String getFirstName() {
return firstName;
}
/** * @return Last name
*/
public String getLastName() {
return lastName;
}
/** * @param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}
/** * @param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}
/** * @param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}
/** * @return ID Returns ID
*/
public long getId() {
return id;
}
/** * @param l Sets the ID
*/
public void setId(long l) {
id = l;
}
}
Corresponding Mapping file
contact.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>
<hibernate-mapping>
<class name="jyoti.ssis.hibernate.Contact" table="CONTACT">
<id name="id" column="ID"><generator class="assigned"></id>
<property name="firstName"><column name="FIRSTNAME"></property>
<property name="lastName"><column name="LASTNAME"></property>
<property name="email"><column name="EMAIL"></property>
</class>
</hibernate-mapping>
Finally the main class where we will use the constructor for getting the pojo class object
SelectHQLExampleUsingConstructor.java
package jyoti.ssis.hibernate;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/** * @author Jyoti Ranjan * * http://www.softidsolutions.com/
Select HQL Example Using Constructor
*/
public class SelectHQLExampleUsingConstructor {
static SessionFactory sessionFactory =null;
public static void main(String[] args) {
Session session = null;
try {
//Get Session From Session Factory
session = getSession();
String s = "Jyoti";
List list = session.createQuery( "select new Contact(c.firstName, c.lastName)from Contact c where c.firstName like '"+s+"'").list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Contact contact = (Contact) iterator.next();
System.out.print("First Name ==>> " + contact.getFirstName());
System.out.println(" Last Name ==>> " + contact.getLastName());
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (session != null) session.close();
}
}
public static Session getSession(){
//Create HibernateSessionFactory
if(sessionFactory==null){
sessionFactory = new Configuration().configure().buildSessionFactory();
}
return sessionFactory.openSession();
}
}
Finally the hibernate configuration file
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd>
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="jyoti/ssis/hibernate/contact.hbm.xml"></session-factory>
</hibernate-configuration>
Run application by setting hibernate required jar files in class path. The out put of the application should come like this on eclipse console:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.
Hibernate: select contact0_.FIRSTNAME as col_0_0_, contact0_.LASTNAME as col_1_0_ from CONTACT contact0_ where (contact0_.FIRSTNAME like 'Jyoti')
First Name ==>> Jyoti Last Name ==>> Ranjan