×
☰ See All Chapters

JPA @EmbeddedId Annotation

If the id field exists in embeddable class (class annotated with @Embeddable) then to embed the embeddable class inside entity class, instead of Id we have to use @EmbeddedId annotation. This embeddable class (class which is annotated with @Embeddable) should implement Serializable interface and should override equals and hashCode methods. We can say @EmbeddedId is another way to add composite primary key in Entity class, instead of IdClass annotation. In this case the composite primary key class is embeddable class i.e. annotated with Embeddable. We have given the details and example for @Embeddable and @Embedded annotation in the previous chapter. We recommend you to refer these annotations if you have not read these in our previous chapters. Now let see an example for @EmbeddedId annotation.

JPA @EmbeddedId Annotation Example

Database script (Mysql Database)

CREATE  TABLE `USER` (  

`USERID` INT NOT NULL ,  

`FIRSTNAME` VARCHAR(45) NULL ,  

`LASTNAME` VARCHAR(45) NULL ,  

`CITY` VARCHAR(45) NULL ,  

`STATE` VARCHAR(45) NULL ,  

`ZIPCODE` NUMERIC(15) NULL,

PRIMARY KEY (`USERID`) );

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> EmbeddedIdAnnotationExample</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name> EmbeddedIdAnnotationExample</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>

 

AddressDetails.java

package com.java4coding;

 

import javax.persistence.Embeddable;

 

@Embeddable

public class AddressDetails {

       

        private String city;

        private String state;

        private int zipCode;

 

        public String getCity() {

                return city;

        }

        public void setCity(String city) {

                this.city = city;

        }

        public String getState() {

                return state;

        }

        public void setState(String state) {

                this.state = state;

        }

        public int getZipCode() {

                return zipCode;

        }

        public void setZipCode(int zipCode) {

                this.zipCode = zipCode;

        }

}

 

PersonalDetails.java

package com.java4coding;

 

import java.io.Serializable;

import javax.persistence.Embeddable;

 

@Embeddable

public class PersonalDetails implements Serializable {

       

        private int userId;

        private String firstName;

        private String lastName;

       

        public int getUserId() {

                return userId;

        }

        public void setUserId(int userId) {

                this.userId = userId;

        }

        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;

        }

 

        @Override

        public int hashCode() {

                final int prime = 31;

                int result = 1;

                result = prime * result

                                + ((firstName == null) ? 0 : firstName.hashCode());

                result = prime * result

                                + ((lastName == null) ? 0 : lastName.hashCode());

                result = prime * result + userId;

                return result;

        }

 

        @Override

        public boolean equals(Object obj) {

                if (this == obj)

                        return true;

                if (obj == null)

                        return false;

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

                        return false;

                PersonalDetails other = (PersonalDetails) obj;

                if (firstName == null) {

                        if (other.firstName != null)

                                return false;

                } else if (!firstName.equals(other.firstName))

                        return false;

                if (lastName == null) {

                        if (other.lastName != null)

                                return false;

                } else if (!lastName.equals(other.lastName))

                        return false;

                if (userId != other.userId)

                        return false;

                return true;

        }

}

User.java

package com.java4coding;

 

import java.io.Serializable;

 

import javax.persistence.Embedded;

import javax.persistence.EmbeddedId;

import javax.persistence.Entity;

import javax.persistence.Table;

 

@Entity

@Table(name = "USER")

public class User implements Serializable {

 

        @EmbeddedId

        private PersonalDetails personalDetails;

       

        @Embedded

        private AddressDetails addressDetails;

 

        public PersonalDetails getPersonalDetails() {

                return personalDetails;

        }

        public void setPersonalDetails(PersonalDetails personalDetails) {

                this.personalDetails = personalDetails;

        }

        public AddressDetails getAddressDetails() {

                return addressDetails;

        }

        public void setAddressDetails(AddressDetails addressDetails) {

                this.addressDetails = addressDetails;

        }

}

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) {

 

                // Create EntityManagerFactory

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

 

                PersonalDetails personalDetails = new PersonalDetails();

                personalDetails.setFirstName("Manu");

                personalDetails.setLastName("Manjunatha");

                personalDetails.setUserId(1);

               

                AddressDetails addressDetails = new AddressDetails();

                addressDetails.setCity("Bangalore");

                addressDetails.setState("Karnataka");

                addressDetails.setZipCode(560001);

               

                // Create Entity

                User user = new User();

                user.setPersonalDetails(personalDetails);

                user.setAddressDetails(addressDetails);

               

                // Create EntityManager

                EntityManager em = emf.createEntityManager();

               

                //Remove the record if already exists

                em.getTransaction().begin();

                if (em.find(User.class, personalDetails) != null) {

                        em.remove(em.find(User.class, personalDetails));

                }

                em.getTransaction().commit();

 

                // Persist entity

                em.getTransaction().begin();

                em.persist(user);

                em.getTransaction().commit();

               

                System.out.println("\n~~~~~~~~~~~~~Persisted user record~~~~~~~~~~~~");

        }

}

Project directory structure

jpa-embeddedId-annotation-0
 

Output:

Hibernate:

    select

        user0_.firstName as firstNam1_0_0_,

        user0_.lastName as lastName2_0_0_,

        user0_.userId as userId3_0_0_,

        user0_.city as city4_0_0_,

        user0_.state as state5_0_0_,

        user0_.zipCode as zipCode6_0_0_

    from

        USER user0_

    where

        user0_.firstName=?

        and user0_.lastName=?

        and user0_.userId=?

Hibernate:

    insert

    into

        USER

        (city, state, zipCode, firstName, lastName, userId)

    values

        (?, ?, ?, ?, ?, ?)

 

~~~~~~~~~~~~~Persisted user record~~~~~~~~~~~~

jpa-embeddedId-annotation-1
 

All Chapters
Author