Hibernate
@Embeddable and @Embedded Example in Hibernate
Meaning of Embedded in general term
The term Embedded refers to something that is strongly integrated within something else. It is a part of an Entity & serve their own purpose within it.
In the context of Hibernate, “embedded” refers to components that are strongly integrated into a larger Entity, typically with a dedicated set of action of his own.
Sounds Confusing? 🤔 Let’s try to understand with an example.
Suppose we have two java classes for two different purposes.
1: Student
2: Certificate
You can download source code here ⬇️
Here we can see Student class have 4 properties i.e id, name, city & certificate. Here we can see property certificate is a Type of Certificate which is integrated withing Student class and serve their own purpose (means provide certificate details like course name & duration.). Here we can see Certificate is embedded in Student class so we can say Certificate class is Embedded class.
Why do we use @Embeddable in Hibernate.
Hibernate has 2 types of Object.
1. Value Object
2. Entities Object
Value Objects are objects that don’t exist independently. Consider the example of a Certificate: when we mention a certificate, people will naturally ask whose certificate it is. So, a Certificate object cannot exist on its own.
On the other hand, Entity Objects are capable of existing independently, like Student.
When dealing with value objects, it’s typically recommended to embed them within an entity object.
Now, why do we create two separate classes?
First and foremost, it’s an Object-Oriented Programming (OOP) principle to promote loose coupling and high cohesion among classes. This means that classes should be designed with a specific and focused purpose. For instance, your Student class should exclusively contain information related to certificate.
Example
pom.xml 👇
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hiber.embeddable </groupId>
<artifactId>EmbeddableHIbernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>EmbeddableHIbernate</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.6.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
</project>
hibernate.cfg.xml 👇
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/embedHiberdb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.hiber.embeddable.Student"/>
<mapping class="com.hiber.embeddable.Certificate"/>
</session-factory>
</hibernate-configuration>
Student.java
package com.hiber.embeddable;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
@Id
private int id;
private String name;
private String city;
@Embedded
private Certificate certificate;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, String city, Certificate certificate) {
super();
this.id = id;
this.name = name;
this.city = city;
this.certificate = certificate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Certificate getCertificate() {
return certificate;
}
public void setCertificate(Certificate certificate) {
this.certificate = certificate;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", city=" + city + ", certificate=" + certificate + "]";
}
}
Certificate.java👇
package com.hiber.embeddable;
import javax.persistence.Embeddable;
@Embeddable
public class Certificate {
private String course;
private String duration;
public Certificate() {
super();
// TODO Auto-generated constructor stub
}
public Certificate(String course, String duration) {
super();
this.course = course;
this.duration = duration;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
@Override
public String toString() {
return "Certificate [course=" + course + ", duration=" + duration + "]";
}
}
EmDemo.java (main class)
package com.hiber.embeddable;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmDemo {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Student student1=new Student();
student1.setId(1);
student1.setName("Sachindra");
student1.setCity("Lucknow");
Certificate certificate1=new Certificate();
certificate1.setCourse("Hibernate");
certificate1.setDuration("2 Months");
student1.setCertificate(certificate1);
Student student2=new Student();
student2.setId(2);
student2.setName("Neha");
student2.setCity("Delhi");
Certificate certificate2=new Certificate();
certificate2.setCourse("Reacts");
certificate2.setDuration("3 Months");
student2.setCertificate(certificate2);
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
// Object save
session.save(student1);
session.save(student2);
tx.commit();
session.close();
factory.close();
}
}
Output:->👇
mysql> select * from student;
+----+-----------+----------+---------+-----------+
| id | course | duration | city | name |
+----+-----------+----------+---------+-----------+
| 1 | Hibernate | 2 Months | Lucknow | Sachindra |
| 2 | Reacts | 3 Months | Delhi | Neha |
+----+-----------+----------+---------+-----------+