×
☰ See All Chapters

JPA @IdClass Annotation

If database table contains compound primary keys, i.e. the primary key is composed of more than one column then compound primary keys can be created in JPA by using either @IdClass or @EmbeddedId annotation. Entity class should be annotated with @IdClass annotation to use identity class objects for identity. Class which is annotated with @IdClass annotation should use the identity class. The @IdClass class has the parameter which accepts the Class object of identity class.

 The Identity class must meet the following criteria:

  1. The class must be public and serializable 

  2. The class must have a public no-args constructor. 

  3. The names of the non-static fields or properties of the class must be the same as the names of the identity fields or properties of the corresponding entity class, and the types must be identical. 

  4. We should override equals() and hashcode()  as these primary key objects need to be identified uniquely.  The equals() and hashcode()  methods of the class must use the values of all fields or properties corresponding to identity fields or properties in the entity class. 

Now let see an example for @IdClass annotation.

JPA @IdClass Annotation Example

Database script

CREATE TABLE STUDENT (

       ID INT NOT NULL,

       FIRSTNAME VARCHAR(20) DEFAULT NULL,

       LASTNAME VARCHAR(20) DEFAULT NULL,

       MARKS INT DEFAULT NULL,

       PRIMARY KEY (ID)

);

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.manum.hassan</groupId>

        <artifactId>IdClassAnnotationExample</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>IdClassAnnotationExample</name>

        <url>https://maven.apache.org</url>

        <dependencies>

                <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>3.8.1</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                        <groupId>org.eclipse.persistence</groupId>

                        <artifactId>javax.persistence</artifactId>

                        <version>2.0.0</version>

                </dependency>

 

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-entitymanager</artifactId>

                        <version>4.2.8.Final</version>

                </dependency>

 

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.11</version>

                </dependency>

        </dependencies>

</project>

 

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

 

        <persistence-unit name="StudentPU">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

 

 

Student.java

package com.java4coding;

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.IdClass;

import javax.persistence.Table;

 

@Entity

@Table(name = "STUDENT")

@IdClass(StudentId.class)

public class Student {

        @Id

        private int id;

 

        private String firstName;

 

        private String lastName;

 

        @Id

        private int marks;

 

        public int getId() {

                return id;

        }

        public void setId(int id) {

                this.id = id;

        }

        public String getFirstName() {

                return firstName;

        }

        public void setFirstName(String firstName) {

                this.firstName = firstName;

        }

        public String getLastName() {

                return lastName;

        }

        public void setLastName(String lastName) {

                this.lastName = lastName;

        }

        public int getMarks() {

                return marks;

        }

        public void setMarks(int marks) {

                this.marks = marks;

        }

}

 

StudentIdentity.java

package com.java4coding;

 

import java.io.Serializable;

import javax.persistence.Id;

 

public class StudentId implements Serializable {

       

@Id

        private int id;

 

        @Id

        private int marks;

 

        public int getId() {

                return id;

        }

        public void setId(int id) {

                this.id = id;

        }

        public int getMarks() {

                return marks;

        }

        public void setMarks(int marks) {

                this.marks = marks;

        }

 

        @Override

        public int hashCode() {

                final int prime = 31;

                int result = 1;

                result = prime * result + id;

                result = prime * result + marks;

                return result;

        }

        @Override

        public boolean equals(Object obj) {

                if (this == obj)

                        return true;

                if (obj == null)

                        return false;

                if (getClass() != obj.getClass())

                        return false;

                StudentId other = (StudentId) obj;

                if (id != other.id)

                        return false;

                if (marks != other.marks)

                        return false;

                return true;

        }

}

 

Test.java

package com.java4coding;

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

 

public class Test {

        public static void main(String[] args) {

                EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU");

                EntityManager em = emf.createEntityManager();

               

                em.getTransaction().begin();

                Student student = new Student();

                student.setFirstName("Manu");

                student.setLastName("Manjunatha");

                student.setId(1);

                student.setMarks(100);

                em.persist(student);

                em.getTransaction().commit();

 

                em.getTransaction().begin();

                em.remove(student);

                em.getTransaction().commit();

        }

}

Project Directory Structure

jpa-idclass-annotation-0
 

Output

Hibernate:

    insert

    into

        STUDENT

        (firstName, lastName, marks, id)

    values

        (?, ?, ?, ?)

Hibernate:

    delete

    from

        STUDENT

    where

        marks=?

        and id=?

 


All Chapters
Author