Newsletter

Part 5 Hibernate Query Language, Passing Runtime Values

Hibernate » on Jul 9, 2011 { 11 Comments } By Sivateja

Now we will see, how to pass the values at time time while using the HQL  select query, actually same concept for 3 cases.

Required files…

  • Product.java (POJO class)
  • Product.hbm.xml  (Xml mapping file )
  • hibernate.cfg.xml  (Xml configuration file)
  • ForOurLogic.java (java file to write our hibernate logic)

Product.java

package str;

public class Product{

	private int productId;
	private String proName;
	private double price;

	public void setProductId(int productId)
	{
	    this.productId = productId;
	}
	public int getProductId()
	{
	    return productId;
	}

	public void setProName(String proName)
	{
	    this.proName = proName;
	}
	public String getProName()
	{
	    return proName;
	}

	public void setPrice(double price)
	{
	    this.price = price;
	}
	public double getPrice()
	{
	    return price;
	}
}

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="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

 

Product.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="str.Product" table="products">

<id name="productId" column="pid"  />
<property name="proName" column="pname" length="10"/>
<property name="price"/>

</class>
</hibernate-mapping>

ForOurLogic.java

 

package str;

import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;

public class ForOurLogic { 

	public static void main(String[] args)
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();		

/* Using label...............

        Query qry = session.createQuery("from Product p where p.productId= :java4s");
        qry.setParameter("java4s",105);

		List l =qry.list();
		System.out.println("Total Number Of Records : "+l.size());
		Iterator it = l.iterator();

		while(it.hasNext())
		{
			Object o = (Object) it.next();
			Product p = (Product)o;
			System.out.println("Product Name : "+p.getProName());
			System.out.println("Product Price : "+p.getPrice());
			System.out.println("---------------------------");

		}		

*/		

/* Using Question Mark  */

		Query qry = session.createQuery("from Product p where p.productId= ?");
	        qry.setParameter(0,105);

			List l =qry.list();
			System.out.println("Total Number Of Records : "+l.size());
			Iterator it = l.iterator();

			while(it.hasNext())
			{
				Object o = (Object) it.next();
				Product p = (Product)o;
				System.out.println("Product Name : "+p.getProName());
				System.out.println("Product Price : "+p.getPrice());
				System.out.println("---------------------------");

			}		

		session.close();
		factory.close();
	}

}

 

Eclipse Console

In The Database

Notes:

  • As i discussed earlier, in the hibernate we can pass the values into the hibernate query at run time also
  • See the commented code from line numbers 1839,  that if we would like to use Label rather question mark symbol
  • See the HQL query in line number 20, i have been used label :java4s [ as a programmer its our responsible to let the hibernate to know its the label not the value, by specifying the colon(:) symbol at starting of label ]
  • In line number 21 i used setParameter method to give the value that’s it.
  • And if you observer line number 41, i used question mark symbol rather label, this time in setParameter method i used zero (0) as first parameter and value in second parameter, remember if use more than one question mark symbol in the query then also the index will starts from zero only

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

11 Responses to “Part 5 Hibernate Query Language, Passing Runtime Values”
  1. Luisa Sedgwick says:

    You got a very superb website, Sword lily I noticed it through yahoo.

  2. utkal samal says:

    Please let me know ,when we pass a runtime value as a Level or as a Question mark? which one is the better approach ?or which one is the recomanded ??????

  3. Java4s says:

    @Utkal samal

    Actually its depends on you friend.
    But i always recommend question marks, as its quick 😉 in most of the real time projects i saw question marks only.

  4. Neeraj+Kashyap says:

    How it is passing the value at runtime coz we are doing setparameter. I mean we have hardcoded the identifier in the next line then how its dynamic query build?

  5. vijay says:

    why parameter start from 0

  6. keshav says:

    sir, setParameter(- ,-) method in which class method.
    thank u for advance

  7. Arpita says:

    Really nice site…Thank you so much guys..for making it so simple

  8. Bharat says:

    As you mentioned above in notes, " remember if use more than one question mark symbol in the query then also the index will starts from zero only". So I want to know How to pass multiple "?" symbols in query.

  9. Anirban says:

    How to pass two run time value in hql.
    the below code does nor working:
    public List<Data> getData(Long id){
    List<Data> list=new ArreyList<Data>();
    SOP(========);
    try
    {
    SOP("Inside Try");
    list=template.find(from Data t where t.acc_no=? and t.status=?, id, "STATIC" );
    } catch(Exception e)
    SOP("" + e.getMessage());
    }
    sop();
    return list;
    }

    Kindly answer ASAP

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.