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 9–12, 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 .:: | ||
Comments
39 Responses to “Example On Composite Primary Keys In Hibernate”
Sweet site, super pattern, really clean and utilize pleasant.
Thank you Henry..!!
java4s ppl rock..!! gonna refer everyone interested in the technology..
@Srikanth
Thanks much friend 🙂
clear and fantastic explanation, excellent site for beginners.. thank u very much for help us this information..
@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.
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
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.
what if one of the field in composite key is foreign key…?
Thanks for your grateful Informations. Here some Basic Hibernate Tutorial
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.
thanks for ur good article.
why we are implementing Serializable interface here. Serializable interface is a marker interface right
why serializable interface is implemented in pojo classes of hibernate?
Nice Website and easy to understandable with out any help.
Please provide the tutorial for webservices.
Awesome tutorial.. Keep it up
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?
Crisp and Clear, to the point…Kudos to you 🙂
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.
Hi,
Give a sample for how to use composite primary key in ManytoOne mapping in hibernate
Really awesome site for the beginners. Easy to understand.
Thank you so much…
Really awesome tutorial..
Thank u so much..
hello, java4s team. Would u like to give me a annotation composite primary keys example ? thanks u so much….
I want to use Composite id with generate class is it possible give a suggestion
thank you very very much
Many many thanks for nice tutorial.
In above example composite Product class should override hashCode() and equals() method or not?
Hey your materiel is just awesome
it helps much for beginner
thank you very much
Hello siva,
please explain why we must implement java.io.serializable in case of composite id.
Thanks in advance.
why serializable interface is implemented in pojo classes of hibernate?
really best Explanation……yar
Why you have created serialVersionUID object in POJO class? What is use of it?
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
Really goood…
Hi Nice example,
May I know how to create the same concept using annotations, means how to create the composite-id concept using annotations.
Good Example
can you tell update hql query for composite primary key
Can you please let us know How can we implemet this using in annotation based?
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
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 .
So good, thanks a lot