Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Hibernate Tutorial >>> Hibernate Composite Key >>> Composite Primary Key
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
Interview Questions
Description : On Hibernate
More...


Written By : Amit
Title :
mapping class hierarchy table per subclass
Description : Example
More...


Written By : Amit
Title :
ways create Hibernate SessionFactory
Description : Example
More...


Written By : Amit
Title :
Spring Hibernate Integration example
Description : Example
More...


Written By : Amit
Title :
ORM Hibernate Best FIT
Description : Discussion
More...


Written By : Amit
Title :
One to Many mapping example
Description : Code
More...

Tags/Keywords : Hibernate Composite Key, Composite primary key, Hibernate, Example, Code, Tutorial, Article
Author : ISHTEK
Date (Year/Month/Date): 2009-06-28 Hibernate Mapping for composite primary key example with code

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

Using Composite Primary key while persisting an Entity in database table
Advertisement :
    Example case study:
Suppose there is a need for persisting an Entity Book in a table book_details. This Entity Book has fields such as bookId, bookName, author, category, price out of which bookId, bookName and author are part of a composite primary key fields in the table book_details. This example has the software environment I have used, as follows: 1. JDK 5.0 (Java Platform) 2. Eclipse 3.2.0 (IDE) 3. Hibernate 3.2 (Hibernate Framework) 4. HSQLDB 1.7.3 (Database) Table book_details DDL script as follows:
HSQLDB compatible create table db script

create table book_details
(book_id integer, book_name varchar(50), author varchar(50), category varchar(50),
 price decimal, primary key (book_id, book_name, author))
Book.java
package example;

import java.io.Serializable;

public class Book implements Serializable {
    private int bookId;
    private String bookName;
    private String author;
    private String category;
    private Double price;
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public int getBookId() {
		return bookId;
	}
	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
}
This is the HBM file with composite-id tag and key-property tags. Composite ids are multiple fields from the POJO that is to be mapped to the corresponding table. book.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 package="example">
  <class name="Book" table="book_details">
    <composite-id>
      <key-property name="bookId" column="book_id"/>
      <key-property name="bookName" column="book_name"/>
      <key-property name="author" column="author"/>				
    </composite-id>
    <property name="category" column="category" type="java.lang.String"/>
    <property name="price" column="price" type="java.lang.Double"/>
  </class>
</hibernate-mapping>
This mapping file has the properties for all the fields from Entity (Book) and database table related composite primary key related information. hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
  <!-- properties -->
    <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
    <property name="connection.url">jdbc:hsqldb:hsql://localhost/</property>
    <property name="connection.username">sa</property>
    <property name="connection.password"></property>
    <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
    <property name="show_sql">true</property>
    <property name="current_session_context_class">thread</property>
    <!-- mapping files -->
    <mapping resource="example/book.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
This hibernate.cfg.xml file has all the properties defined to be used while creating Hibernate SessionFactory. This configuration file has the mapping file "book.hbm.xml" file path as well. In order to testing this example, we may require a Test Client, that I have already written and as follows: This test client just creates a Hibernate SessionFactory and then gets the Hibernate Session from the SessionFactory. Now this Session is used to persist Book instance with some dummy values for all the fields, including composite key mapped fields, such as bookId, bookName, author. Client.java
package example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Client {
    //Hibernate SessionFactory
    SessionFactory sessionFactory;
    public Client() {
    //Hibernate Configuration
      Configuration conf = new Configuration();
     //Loading configuration properties file and building Hibernate SessionFactory.
      sessionFactory = conf.configure("hibernate.cfg.xml").buildSessionFactory();
      if(sessionFactory != null) {
        Session session = sessionFactory.getCurrentSession();
        Transaction trans = session.getTransaction();
        trans.begin();
        Book bk = new Book();
        bk.setBookId(1);
        bk.setBookName("Hibernate Examples");
        bk.setAuthor("ISHTEK");
        bk.setCategory("Hibernate Framework");
        bk.setPrice(new Double("100.50"));
        session.save(bk);
        session.flush();

        Book bk1 = new Book();
        bk1.setBookId(1);
        bk1.setBookName("Hibernate Examples");
        bk1.setAuthor("ISHTEK");
        Book bk2 = (Book) session.load(Book.class, bk1);
        System.out.println("Category : "+ bk2.getCategory()
                         + "\nPrice : "+bk2.getPrice().toString());
        trans.commit();
      }
		
    }
   
   /**
    * @param args
    */
    public static void main(String[] args) {
      new Client(); 
    }

}
After running this client, I could able to persist book instance as defined in this program, and was able to retrieve this Book Entity from database. I tried many ways to break this examples composite keys integrity or test for negative scenarios, such as didn't pass author name to the Book Entity and tried to save this in database, but found Exception.
Advertisement :
Hope this helps in studying Composite primary key Hibernate mapping functionality.
Author of this article/writeup has expressed his/her willingness
to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).


	

Commented By ->
igal
Hi

Thanks for the example.

Shouldn't the execution of the code create the database automaticlly?

I run in using MySQL and I got the following error:
 java.sql.BatchUpdateException: Table 'ee.book_details' doesn't exist


Thanks
Igal
Are you interested in solving a very interesting Technology Stack while Playing this Game          

Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
26,8
Enter bigger number from above :*
Home >>> Hibernate Tutorial >>> Hibernate Composite Key >>> Composite Primary Key
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
Referred By Name *:
Resource URL *: (e.g, URL should be starting with http://www.-----.---)
 
Resource Short Description *:
31,32
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER
Terms of Use and Disclaimer :

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed materials, content of these pages may 
become out of date over a period of time. Therefore all visitor/users of this web 
site are requested/advised to refer to the originating parties/sources for the 
latest changes and happenings for detailed information. This information is not 
intended to be a substitute for the original reference provided by the originating 
parties/sources.

By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or 
downloading any materials, you agree to and are bound by the terms of use 
described in this page and Usage Terms and Conditions. 
If you do not agree to all of 
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this 
website in any manner. If you are using the website on behalf of your 
employer, you represent that you are authorized to accept these Terms of Use 
on your employer's behalf.

All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any 
of these information, please refer original content/documentation from respective sources. 
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.