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.