Newsletter

Example On Composite Primary Keys In Hibernate

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

Composite primary keys means having more than one primary key, let us see few points on this concept

  • If the table has a primary key then in the hibernate mapping file we need to configure that column by using <id /> element right..!
  • Even though the database table doesn’t have any primary key, we must configure one column as id (one primary key is must)
  • If the database table has more than one column as primary key then we call it as composite primary key, so if the table has multiple primary key columns , in order to configure these primary key columns in the hibernate mapping file we need to use one new element called <composite-id …..> </composite-id>

 

Example On this__

Files required….

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

 

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="proName" column="pname" length="10" />
</composite-id>

<property name="price"/>

</class>
</hibernate-mapping>

 

ForOurLogic.java

package str;

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

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();

		Product p=new Product();

		p.setProductId(101);
                p.setProName("iPhone");
                p.setPrice(25000); 

	       Transaction tx=session.beginTransaction();
	          session.save(p);
	          System.out.println("Object Loaded successfully.....!!");
	       tx.commit();     

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

}

Eclipse output

In the database

Notes:

  • see Product.java pojo class, in line number 3 i have implemented the java.io.Serializable interface,  this is the first time am writing this implementation for the pojo class right…!  we will see the reason why we use this serializable interface later.
  • But remember, if we want to use the composite primary keys we must implement our pojo class with Serializable interface
  • hibernate.cfg.xml is normal as previous programs, something like hello world program
  • come to Product.hbm.xml, see line number 912, this time we are using one new element<composite-id>
  • Actually if we have a single primary key, we need to use <id> element, but this time we have multiple primary keys, so we need to use this new element <composite-id>
  • Actually we will see the exact concept of this composite primary keys in the next example (loading an object with composite key)

​​

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

39 Responses to “Example On Composite Primary Keys In Hibernate”
  1. Sweet site, super pattern, really clean and utilize pleasant.

  2. java4s.com says:

    Thank you Henry..!!

  3. Srikanth says:

    java4s ppl rock..!! gonna refer everyone interested in the technology..

  4. Java4s says:

    @Srikanth

    Thanks much friend 🙂

  5. venkat says:

    clear and fantastic explanation, excellent site for beginners.. thank u very much for help us this information..

  6. Java4s says:

    @Venkat

    You welcome my friend, am really happy to see such great feedback from you, feel free to share our blog with your friends, thanks.

  7. vishal says:

    Hi,
    can you please tell me which annotation we use for composite key in hibernate.if you give me an annotated class with composite key then is much better.

    Thanks & Regards
    Vishal Singh

  8. kiran says:

    Hi Java4s,

    Its a good tutorial for learning required technologies with very good and short examples.. i am on my journey to complete the Hibernate i read and got good knowledge up to this article (Composite-Primary Key). i’d say at last what Java4s is… when i finished this hibernate…

    Thanks & Regards
    Kiran.

  9. vishal says:

    what if one of the field in composite key is foreign key…?

  10. Raghu says:

    Thanks for your grateful Informations. Here some Basic Hibernate Tutorial

  11. Good example. But there other ways of implementing composite primary key in hibernate. I mean you can use separate class class as composite primary key and there is also xml syntax for creating composite primary key that have its one of field having many-to-one association. Can you please throw light on overriding compareTo and equals method for primary key class.

  12. suresh says:

    thanks for ur good article.
    why we are implementing Serializable interface here. Serializable interface is a marker interface right

  13. why serializable interface is implemented in pojo classes of hibernate?

  14. usharani says:

    Nice Website and easy to understandable with out any help.
    Please provide the tutorial for webservices.

  15. olymohamed says:

    Awesome tutorial.. Keep it up

  16. samba siva rao chinta says:

    Hi, siva teja u r tutorial is amazing and it giving wonderful knowledge to many people…………!
    and can i ask a qustion on hibernate;

    What is a surrogate key and when can i use #surrogate in an application?

  17. Jagdish says:

    Crisp and Clear, to the point…Kudos to you 🙂

  18. John says:

    Hi Siva, I have a question. Can you show the example of select from some table which has left outer join on View by some id that belongs to View’s composite primary key? And preferably with Hibernate-4. Thank you.

  19. Ravi says:

    Hi,
    Give a sample for how to use composite primary key in ManytoOne mapping in hibernate

  20. Mohit says:

    Really awesome site for the beginners. Easy to understand.
    Thank you so much…

  21. Narasimha Reddy says:

    Really awesome tutorial..

    Thank u so much..

  22. Hung Nguyen says:

    hello, java4s team. Would u like to give me a annotation composite primary keys example ? thanks u so much….

  23. Chandrasekhar rao says:

    I want to use Composite id with generate class is it possible give a suggestion

  24. rajnish says:

    thank you very very much

  25. Harish Chandra says:

    Many many thanks for nice tutorial.

    In above example composite Product class should override hashCode() and equals() method or not?

  26. Mukesh says:

    Hey your materiel is just awesome
    it helps much for beginner
    thank you very much

  27. Swarna says:

    Hello siva,
    please explain why we must implement java.io.serializable in case of composite id.

    Thanks in advance.

  28. Ravi says:

    why serializable interface is implemented in pojo classes of hibernate?

  29. sid says:

    really best Explanation……yar

  30. Ritz says:

    Why you have created serialVersionUID object in POJO class? What is use of it?

  31. Abhilash says:

    i think their is one problem in it, if we assign both the parameters as primary key. Then only one parameters works and the other wont

  32. priya says:

    Really goood…

  33. aditi says:

    Hi Nice example,
    May I know how to create the same concept using annotations, means how to create the composite-id concept using annotations.

  34. kolanjinathan says:

    Good Example

  35. UMAMAHESWARARAO PUCHHAKAYALA says:

    can you tell update hql query for composite primary key

  36. Mukesh says:

    Can you please let us know How can we implemet this using in annotation based?

  37. kuldeep singh says:

    thanks you sir,
    I love to write code that is not possible with annotation. Most of the resources of information use annotation but you are using mapping file. this is really helpful.
    thank you very much sir

  38. ramesh says:

    i have separated the composite keys (customer_name,customer_id) in to a separate class now .. what if want to have a autogenerated id inside the composite id class …how can i do that ?

    the <composit-ket> element doesnot allow you to have <generator class="" > element .

  39. huynhhoa says:

    So good, thanks a lot

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.