Newsletter

Composite Primary Key In Hibernate With Select Query

Hibernate » on Jun 24, 2011 { 25 Comments } By Sivateja

Composite primary keys means having more than one primary key right..?

Example On this__

Files required….

  • Product.java (Pojo)
  • ForOurLogic4Load.java (for our logic)
  • hibernate.cfg.xml
  • Product.hbm.xml

All files are same like previous program, but ForOurLogic4Load.java is the new file for loading an object from the database

Product.java

package str;

public class Product implements java.io.Serializable{

	private static final long serialVersionUID = 1L;

	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">

<composite-id>
<key-property name="productId" column="pid"  />
<key-property name="price" />
</composite-id>

<property name="proName" column="pname" length="10"/>

</class>
</hibernate-mapping>

 

ForOurLogic4Load.java

package str;

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

public class ForOurLogic4Load { 

	public static void main(String[] args)
	{

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

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

		Product p=new Product();

		p.setProductId(101);
	    p.setPrice(25000);

	    Object o=session.get(Product.class, p);
	    // here p must be an serializable object,

	    Product p1=(Product)o;

	    System.out.println("The price is: "+p1.getProName());	    

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

}

Eclipse output

Notes:

    • regarding ForOurLogic4Load.java actually for loading an object we have to pass the primary key column value like…
Object o=session.get(Product.class, new Integer(101));
    • Actually that is the case with single primary key, but see in this example we are using multiple primary keys (2 primary key values), so while loading an object how we will give two values….?
Object o=session.get(Product.class, new Integer(101,25000));
  • πŸ™‚ which is absolutely wrong……………!!!!!!!!!
  • so how we can pass the multiple primary key values for loading that object.. ?
      • First we need to set the values just like in line numbers 19,20 , ensure you are setting the values which already have in the database for that particular object.
      • Then we need to pass that object as the parameter to load the object.
    Object o=session.get(Product.class, p);
      • What am saying is that the second parameter of the get method is always a Serializable object, so in the Product.java line number 3 i just implemented with java.io.Serializable
      • Remember, if we have single primary key we used to give
    Object o=session.get(Product.class, new Integer(101));

    here new Integer(101) is the wrapper, all wrappers are Serializable by default.

​ ​​

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

25 Responses to “Composite Primary Key In Hibernate With Select Query”
  1. Srinivas.G says:

    Excellent explanation….thanks

  2. Java4s says:

    @Srinivas

    You bet, thanks for your feedback πŸ™‚

  3. Amarnath says:

    Thanks for the nice expalnation with clarity.

  4. Hai, this is venkatarao , you r really god to me and all java developers. , i love your website(www.java4s.com) . really thanqs . sir please provide webservicess meterial

  5. Kanna says:

    Very nice explanation.
    I stuck up with these in some interviews

  6. ramu says:

    Hi Thank you for clear explanation. Actually i have one doubt here,If we have only one single primary key in database table and can we use get method by making the pojo as serializable?

  7. basha says:

    Hi,

    Your explanation is very clear,My doubt is without using save() method how could you get data from database by using get() method.
    –>what is difference between get() & load().

  8. really excellent explanation regarding serializable object.

    thnx a lot..

  9. Swamy Nadhan says:

    Hi,

    This tutorial was very helpfull…….

    Thanks
    πŸ™‚

  10. charan says:

    hello boss ur teaching style is very good…can u provide jquery and ajax clealy

  11. Chandan Prasad says:

    Hi,
    How to get more than one row data from database.
    currently i have got “org.hibernate.HibernateException : More than one row with the given identifier was found: str.Product@b59fd9, for class: str.Product”
    when ever i get more than one row of data.

    Thanks

  12. Aamir says:

    Hi Sivateja how r u, I just have one question, what if we have a reference in composite key class, then how can we do mapping in composite-id tag for it.

    i.e,

    class Address {
    private String city;
    private String state;

    //getters and setters.
    }

    class CompKey implemenst Serializable {

    private String firstName;
    private String email;
    private Address address;
    }

    now, how to use address ref. variable in composite-id tag???

  13. Ashok says:

    Why we write Product p1=(Product)o;……..without directly print object o.ProName();

    I want to Know what type of data is there in object o and P1…….please tell me.

    thanks a lot.

  14. madhu says:

    really,very nice explanation.

  15. Raju Kapadne says:

    Hello Sir ,

    Really java4s.com is extremely good and easy to learn the tutorials . . Thanks a lot sir !!

  16. BoopathyCovai says:

    Hi Java4s,
    your website is awesome for new comers.
    I am having one doubt, is this only for multiple primary key ?
    suppose if i want to pass 3 or 4 parameters(those or not primarykey).
    what will do for this ?

  17. sudheer k says:

    Excellent website for java learners.. But, one small doubt, why Product class must be serialize ? and without save object how can we get that Object from DB using session.get() method.. PLz let me know..

  18. aashish soni says:

    why composite id class must implement serializable??
    Then why single-id class doesn’t need to be Serializable? Could you elaborate on that?

  19. Rohit says:

    Excellent explanation…thanks πŸ™‚

  20. usha says:

    Good Explanation and thank you. could you please give some example on updating record of a table having composite keys(of varChar type(String)).

  21. Tirupathi says:

    HI.
    Here i am getting NullPointerException when i am retring the data from DB. can you plz explain

    Exception in thread “main” java.lang.NullPointerException
    at str.ForOurLogic4Load.main(ForOurLogic4Load.java:27)

  22. prasanna says:

    Hi..
    iam also getting the Exception is

    Exception in thread β€œmain” java.lang.NullPointerException
    at str.ForOurLogic4Load.main(ForOurLogic4Load.java:27)

    can u pls help me.

  23. Deepa says:

    @Prasanna and @Tirupathi
    You have update the code in file ForOurLogic4Load.java at line number 20, to p.setProName("iphone") .
    As product id and product name are composite primary keys, so we need to pass both the values in order to get price.

  24. Hunt says:

    One of the best blog to study hibernate.

    Thanks

  25. You are amazing dear nice concept other sites are much confusing …

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.