Home » Enterprise Java » jpa » Embedded compound primary key in JPA

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Embedded compound primary key in JPA

With this example we are going to demonstrate how to create an embedded compound primary key in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. A composite primary key is usually made up of two or more primitive or JDK object types. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. You can specify such a composite primary key with a separate composite primary key class.

Here, we create a class that is an embedded compound primary key, as described below:
 
 

The StudentId class

The StudentiD class is an embedded compound primary key class, that consists of two properties. It is annotated as @Embeddable, to defines that its instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity.

package com.javacodegeeks.snippets.enterprise;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class StudentId implements Serializable {
	
	private static final long serialVersionUID = 590496859747051370L;




	@Column
	private int id;

	private String country;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	@Override
	public String toString() {
		return "StudentId [country=" + country + ", id=" + id + "]";
	}

}

The EmbeddedCompoundPrimaryKeyInJPA class

In EmbeddedCompoundPrimaryKeyInJPA class we create an EntityManagerFactory interface to interact with the entity manager factory for MyPeristenceUnit, that is defined in persistence.xml file. We create an EntityManager, using the createEntityManager() API method. Then, we create a new StudentId object. The new object is writen to the database, using the persist(java.lang.Object entity) API method of EntityManager. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a persist so that a transaction begins and ends. The object can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager.

package com.javacodegeeks.snippets.enterprise;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EmbeddedCompoundPrimaryKeyInJPA {
	
	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		
		EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		StudentId studentId = new StudentId();
		studentId.setId(1);
		studentId.setCountry("Greece");
		
		Student student = new Student();
		student.setId(studentId);
		student.setName("Joe Doe");
		
		em.persist(student);
		
		em.getTransaction().commit();
		
		em.getTransaction().begin();
		
		Student dbStudent = em.find(Student.class, studentId);
		System.out.println("dbStudent " + dbStudent);
		
		em.getTransaction().commit();
		
		em.close();
	    emf.close();

	}

}

persistence.xml
The settings of the database configuration are defined in persistence.xml file.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
	
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.username" value="jcg" />
			<property name="hibernate.connection.password" value="jcg" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost/companydb" />
		</properties>
	</persistence-unit>
	
</persistence>

Output:

dbStudent Student [id=StudentId [country=Greece, id=1], name=Joe Doe]

 
This was an example of how to create an embedded compound primary key in JPA.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of