Hibernate: composite key example

hibernate_logo
Why Composite key required in database? when you have to combine multiple key and would like to form a primary key. or you can say when you want a primary key by combining of more than one key. And you know, primary key is unique and not nullable in database.

You can visit our hello world Hibernate program to download required jar files. You can find download source code at the end of hello worlds article, in which you can put this code step by step and run this example of composite key.

1. Overview of composite key

First of all, you should understand, why composite key is required ?
Primary key is basically provide unique and not null column, if you want to s primary key by combining of multiple key, what will you do? You can combine multiple key and form a primary key. At the end the post you learn how to do a composite key in hibernate.

2. POJO/domain model class

File: com/mysoftkey/composite/Book.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.mysoftkey.composite;
 
import java.io.Serializable;
 
public class Book implements Serializable {
  private int bookId;
  private String bookName;
  private String author;
  private String category;
  private Double price;
 
  // generate setter/getter property, removed this for simplicity
}

3. Hibernate mapping file

This is mapping file between java and hibernate. here, primary key by combining of bookId, bookName, and author

File: book.hbm.xm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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 auto-import="false"
	package="com.mysoftkey.composite">
  <class name="Book" table="book_compsite_key">
	<composite-id>
	<key-property name="bookId" type="integer">
		<column name="book_id"></column>
	</key-property>
	<key-property name="bookName">
		<column name="book_name"></column>
	</key-property>
	<key-property name="author">
		<column name="author"></column>
	</key-property>
	</composite-id>
 
	<property name="category" column="category" type="string" />
	<property name="price" column="price" type="java.lang.Double" />
 
  </class>
 
</hibernate-mapping>

4. Hibernate configuration xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_example</property>
	<property name="hibernate.connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="connection.pool_size">1</property>
	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	<property name="show_sql">true</property>
	<property name="hbm2ddl.auto">create</property>
 
	<!-- Composite key example -->
	<mapping resource="com/mysoftkey/composite/Book.hbm.xml"/>
 
 </session-factory>
</hibernate-configuration>

5. Run Composite key Hibernate example

This is main class to run the composite key example in Hibernate.

File: com/mysoftkey/composite/CompositeKeyBookClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.mysoftkey.composite;
 
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
 
import com.mysoftkey.util.HibernateUtil;
 
/**
 * this the entry point of the application to test composite key in hiberante.
 * 
 * @author ranjeet jha
 *
 */
public class CompositeKeyBookClient {
 
  /**
   * This is main method to run the application.
   * 
   * @param args
   */
  public static void main(String[] args) {
 
    // Open Hibernate session from sessionFactory.
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
 
    try {
 
      // begin Trasaction
      transaction = session.beginTransaction();
 
      // create pojo and populate info
      Book book = new Book();
      book.setBookId(1);
      book.setBookName("Hibernate Professional");
      book.setAuthor("wrox");
      book.setCategory("advance");
      book.setPrice(new Double("1234.78"));
 
      // save book object into database
      session.save(book);
 
      // commit transaction
      transaction.commit();
    } catch (HibernateException e) {
 
      // roll back transaction
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
 
  }
 
}

6. Output of composite key example

Eclipse Console ouptput:

1
2
3
4
5
6
7
8
9
10
14 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.0.GA
31 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
38 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
45 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
87 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
209 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : com/mysoftkey/composite/Book.hbm.xml
261 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: com.mysoftkey.composite.Book -> book_compsite_key
897 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - schema export complete
 
Hibernate: insert into book_compsite_key (category, price, book_id, book_name, author) values (?, ?, ?, ?, ?)

mysql console output:

mysql> SELECT * FROM book_compsite_key;
+---------+------------------------+--------+----------+---------+
| book_id | book_name              | author | category | price   |
+---------+------------------------+--------+----------+---------+
|       1 | Hibernate Professional | wrox   | advance  | 1234.78 |
+---------+------------------------+--------+----------+---------+
1 ROW IN SET (0.00 sec)
 
mysql>

Your comments are welcome to improve this post (how to use composite key in Hibernate). Happy Learning of composite key in Hibernate :)

Please follow and like us:
RSS
Follow by Email
Facebook
LinkedIn
Google+

Leave a Reply

Your email address will not be published. Required fields are marked *