Tech I Enjoy Logo

Custom Search




  Home >> Hibernate


Using Composite Primary key while persisting an Entity in database table

    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. Hope this helps in studying Composite primary key Hibernate mapping functionality. If you like to share your comment/suggestions/feedback relating to this Page, you can do so by droping us an email at usingframeworks @ gmail . com with the subject line mentioning URL for this Page (i.e, /Hibernate-composite-primary-key.php) or use this LINK. As per this website's privacy policy, we never disclose your email id, though we shall post your comments/suggestions/feedback with your name (optional) and date on this Page. If you don't want your comments/suggestions/feedback to be shared in this Page, please mention so in your email to us. Thank you very much..... If anything missed out , please let me know at techienjoy at yahoo . com
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Interview Questions :
Interview Questions on Hibernate with answer.
List of Examples on Hibernate :
List of example using Hibernate.
Hibernate Property Formula :
Hibernate Example on Property
Tag with ease to do code walk-through
Hibernate Transaction on JBoss :
Explaining Transaction using Hibernate
on JBoss Application Server.
Hibernate Example on Filter Criteria :
Example on using Filter Criteria
using Hibernate Framework to work with.
Hibernate Interceptor Example :
Example on using Interceptor using Hibernate Framework
with source code explained.
Hibernate one to one mapping Example :
one to one mapping explained using an example
and Hibernate Framework.
Hibernate Insert Update control :
Hibernate Example on controlling
insert and update attributes
Class Hierarchy Mapping Example :
class hierarchy mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate Named Query Example :
Named Query markup using an example
and Hibernate Framework.
Hibernate Component Property :
Hibernate Example on Component 
with source code explained.
Hibernate class heirarchy mapping :
Hibernate Example on mapping
class hierarchy using various ways
of persisting into database
tables.
Example on persisting Class Hierarchy :
Example on using Hibernate Framework
to persist Class Hierarchy into database.
Hibernate Many to Many Mapping Example :
Many to many mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate Join Example :
Using Table join explained with an example
while using Hibernate Framework.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Example on composite Primary key :
Example on using Hibernate Framework
to work with mapping using composite
Primary key.
Hibernate Bag Mapping Example :
class mapping using Bag Tag example using Hibernate
Framework and a simple to follow steps.
Hibernate Example on Filter :
Example on using Filter using Hibernate Framework
to work with.


References :
Tags: Hibernate Class Hierarchy Persist example
Tags: Hibernate composite primary key
Tags: Hibernate criteria filter example
Tags: Hibernate Filter Example
Tags: Hibernate Interceptor example
Tags: Hibernate Interview Questions
Tags: Hibernate join example
Tags: Hibernate Many to Many Mapping Example
Tags: Hibernate mapping bag
Tags: Hibernate mapping class hierarchy table per subclass
Tags: Hibernate named query markup
Tags: Hibernate One to Many mapping example
Tags: Hibernate One To One Mapping Example
Tags: Hibernate scenario one to many
Tags: Hibernate transaction jboss
Tags: Hibernate



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions