Newsletter

Example On Hibernate Select Query

Hibernate » on Jun 12, 2011 { 18 Comments } By Sivateja

This is an example for loading the object from the database remember in the hibernate loading 1 object from the database means applying select command (select * from _____) for fetching one complete record from the database.

Files required to execute this program..

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

 

Product.java (POJO)

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;
	}
}

 

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>

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>

ClientProgram.java

package str;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class ClientProgram { 

	public static void main(String[] args)
	{

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

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();
		Object o=session.load(Product.class,new Integer(101));
		Product s=(Product)o;
		// For loading Transaction scope is not necessary...
		System.out.println("Loaded object product name is___"+s.getProName());

		System.out.println("Object Loaded successfully.....!!");
		session.close();
		factory.close();
	}

}

Now compile all .java files and run ClientProgram.java to see the output

Eclipse Output

 

In the database

Note:

  • In this program Product.java is just pojo class nothing special
  • Mapping and Configuration files are just like previous programs
  • But in ClientProgram.java, see in line number 16 load(-,-) method which is in the session, actually we have 2 methods to load the object from the database, they are load and get i will explain when time comes, as of now just remember this point
  • Now see line number 19,  we are going to print the product name by writing +s.getProName
  • Actually once we loaded the object for the database with load or get methods the object data will be loads into the Product.java(POJO) setter methods, so we are printing by using getter methods

 

​​

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

18 Responses to “Example On Hibernate Select Query”
  1. Mohammed Vaseem says:

    Hello Java4s,
    I modified this program a little bit and getting some exceptions.
    Taken Product class attributes as
    private int productId;
    private String productName;
    private int productPrice;

    Configured this Product.class in Products.hbml.xml file. Products.hbml.xml is successfully configured in hibernate.cfg.xml file.

    In your program @ line 19, we are retrieving object from database via a class object. for this we used
    System.out.println(“Loaded object product name is___”+s.getProName()); (as per your program)

    My doubt:
    i wrote in my program like this,
    System.out.println(“Product id is : “+p.getProductId());
    System.out.println(“Product name is : “+p.getProductName());

    Product id is printing successfuly but productname is not printing and showing exception as
    No row with the given identifier exists: [Product#101]

    What is the reason behind this? Please help.

  2. Mohammed Vaseem says:

    I got solution for this. My mistake is, i kept
    create but not update.
    So every time whenever the program is execution is commenced, a new table is being created by deleting the previous table. So newly created table is always empty. I think am right.

  3. Java4s says:

    @ Vaseem

    Coollll
    Seems you are playing with configuration file, hbm2ddl.auto.

    You are correct, actually you are not specified that you changed configuration file, that’s why i little confused.

  4. Mohammed Vaseem says:

    Hello,
    I learning is all about playing… and I think We can learn better by playing only.

  5. Veera says:

    how can i know which database name i’ll choose in oracle database….

  6. Vishal says:

    Hi Admin,

    First of All Thank you very Much for this.

    I have one doubt in Line no. 21 of ClientProgram.java
    Object o=session.load(Product.class,new Integer(101));

    How the Hibernate ensures that Integer 101 belongs to PID itself??

    Thanks and regards

    Vishal

  7. prasad says:

    hi boss
    i have a doubt single row display is good,
    how to display total table in a specific database

  8. Sourov says:

    Object o = session.load(Product.class,new Integer(101));
    Product s = (Product)o;

    Since I have fetched ‘Product.class’,
    then can u make me clear pls, why did u cast here?

  9. Narasimha says:

    Hi sir,

    for load and get no need transaction object this for your information..please clarify is i am wrong

    Configuration configuration = new Configuration()
    .configure(“hibernate.cfg.xml”);
    SessionFactory sf = configuration.buildSessionFactory();
    Session session = sf.openSession();
    //Transaction transaction = session.beginTransaction();
    Product product=(Product) session.get(Product.class, new Integer(200));
    System.out.println(product.getpName());
    System.out.println(product.getPrice());
    System.out.println(product.getProductID());
    //transaction.commit();

  10. arch says:

    Hi vishal
    Answer to your question is , as we have specified PID as in product.hbm.xml.so this select query will select the row on the basis of PID .thats why hibernate ensures Interger 101 as PID .

  11. Rajyalaxmi says:

    There is nothing wrong in your code and if u want to fetch complete table info from DB then u shud go for HQL,this is for bulk operations

    This wil also work:::::::::::
    Instead of Product p=(Product)session.get(“Product”,101);
    Query query=session.createQuery(“from Product p”);

  12. silambarasu says:

    sir,
    Could not parse configuration: hibernate.cfg.xml
    i run in linux command prompt.i put all source file in same folder.logs files are stored.tell me sir

  13. Venugopal says:

    Excellent tutorial website. Can you please help me in learning AngularJS latest version.
    Thanks in advance.

  14. rakesh says:

    when i run hibernate application i'm getting exception….help me to get out from this
    Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
    at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
    at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
    at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:409)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:119)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2006)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1289)
    at com.hibernate1.Test_Cus_Ven.main(Test_Cus_Ven.java:19)

  15. Prashant says:

    I think you have to specify database name explicitly in mapping file like..
    <class name="str.Product" table="products" schema ="your database name">

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.