×
☰ See All Chapters

JPA @Embeddable and @Embedded Annotation

A class annotated with @Embeddable annotation will not have independent existence. We cannot run DB queries, without depending on other class. An instance of an embeddable class, on the other hand, is only stored as part of a separate entity. Embeddable instances have no persistent identity, and are never returned directly from the EntityManager or from a Query unless the query uses a projection on owning class to the embedded instance. For example, if Address is embedded in User, then a query "SELECT a FROM Address a" will never return the embedded Address of User; but a projection query such as "SELECT u.address FROM User u" will. Typically, embeddable classes share the same table as the Entity in which they are embedded. If the id field exists in embeddable class (class annotated with Embeddable) then to embed the embeddable class inside entity class, instead of @Embedded we have to use @EmbeddedId annotation. In this case embeddable class (class which is annotated with @Embeddable) should implement Serializable interface and should override equals and hashCode methods,

What is the necessity of using @Embeddable annotation

Consider a User table with the columns firstname, lastname, userId, city, state, zipcode. In java it is good to have two separate data classes (POJO classes) like Personal details class and Address details class. So these two classes can be annotated with Embeddable and finally User entity class can embed these two classes using Embedded. If personal details/address details class does not present then we can have the variable/fields in User entity class itself and can embed the embeddable class whichever available. Now let see example for Embeddable and Embedded annotation.

JPA @Embeddable and @Embedded annotation example

Database script (Mysql Database)

DROP TABLE STUDENT;

COMMIT;

 

CREATE  TABLE `STUDENT` (  

`STUDENTID` 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 (`STUDENTID`) );

COMMIT;

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

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>EmbeddableAnnotationExample</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 java.io.Serializable;

 

import javax.persistence.Embedded;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.IdClass;

import javax.persistence.Table;

 

@Entity

@Table(name = "STUDENT")

public class Student implements Serializable {

 

        @Id

        private int studentId;

        private String firstName;

        private String lastName;

       

        @Embedded

        private StudentAddress studentAddress;

 

        public int getStudentId() {

                return studentId;

        }

        public void setStudentId(int studentId) {

                this.studentId = studentId;

        }

        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 StudentAddress getStudentAddress() {

                return studentAddress;

        }

        public void setStudentAddress(StudentAddress studentAddress) {

                this.studentAddress = studentAddress;

        }

}

StudentAddress.java

package com.java4coding;

 

import javax.persistence.Embeddable;

 

@Embeddable

public class StudentAddress {

        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;

        }

}

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("StudentPU");

 

                // Create Entity

                Student student = new Student();

                student.setFirstName("Manu");

                student.setLastName("Manjunatha");

                student.setStudentId(1);

 

                StudentAddress address = new StudentAddress();

                address.setCity("Bangalore");

                address.setState("Karnataka");

                address.setZipCode(560001);

               

                student.setStudentAddress(address);

               

                // Create EntityManager

                EntityManager em = emf.createEntityManager();

               

                //Remove the record if already exists

                em.getTransaction().begin();

                if (em.find(Student.class, 1) != null) {

                        em.remove(em.find(Student.class, 1));

                }

                em.getTransaction().commit();

 

                // Persist entity

                em.getTransaction().begin();

                em.persist(student);

                em.getTransaction().commit();

 

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

        }

}

Project directory structure

embeddable-and-embedded-annotation-0
 

Output:

Hibernate:

    select

        student0_.studentId as studentI1_0_0_,

        student0_.firstName as firstNam2_0_0_,

        student0_.lastName as lastName3_0_0_,

        student0_.city as city4_0_0_,

        student0_.state as state5_0_0_,

        student0_.zipCode as zipCode6_0_0_

    from

        STUDENT student0_

    where

        student0_.studentId=?

Hibernate:

    insert

    into

        STUDENT

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

    values

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

 

~~~~~~~~~~~~~Persisted student record~~~~~~~~~~~~

embeddable-and-embedded-annotation-1
 

All Chapters
Author