Home >> Hibernate
Using Composite Primary key while persisting an Entity in database table
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