0% found this document useful (0 votes)
24 views6 pages

Embed Object

Uploaded by

SakethBharadwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views6 pages

Embed Object

Uploaded by

SakethBharadwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Embed_object

Hibernate @Embeddable and @Embedded Annotations


Here we show how to embed one entity inside another entity, so they are mapped to a single table. With Hibernate we can use
the @Embeddable annotation to mark a class to be eligible as an embeddable class.

We can use the @Embedded annotation to embed an embeddable class. The attributes of an embedded class can be overridden using
the @AttributeOverrides and the @AttributeOverride annotations.

Technologies and tools used


• Hibernate 6.1.7.Final

• IDE - Eclipse

• Maven 3.5.3

• JavaSE 17

• MySQL - 8.0.32

1. Create a Simple Maven Project


Tools and technologies used
• Eclipse Neon

• Maven - 3.5.3

• JDK - 1.8

Let's create step by step a simple maven project in Eclipse IDE.

Step-1
• Open Eclipse

• Click on File -> New -> Maven Project

Step-2

Java_ Page 1
Step-2
Click on Checkbox for both

• Create a simple project

• Use default Workspace location

• Click on next button

Step-3
Provide GroupId and ArtifactId in next screen.

• GroupId: net.tr.maven-demo

• Artifact Id: maven-demo-project

• Name: maven-demo-project

• Description: Simple Maven Demo Project

2. Project Directory Structure


The project directory structure for your reference -

Java_ Page 2
3. Add jar Dependencies to pom.xml
We use Apache Maven to manage the project's dependencies. Add the following dependencies to your project's pom.xml file.
<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>
<parent>
<groupId>net.tr.hibernate</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>hibernate-Embaddable-example</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.7.Final</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

4. Creating an Embeddable Class using @Embeddable


Let's create Address and Name classes as Embeddable classes.

The advantage of using embedded objects is that they are reusable and you can map two entities to the same database table.

4. Creating an Embeddable Class using @Embeddable


Let's create Address and Name classes as Embeddable classes. The advantage of using embedded objects is that they are reusable and you can map two entities to the same database table.

Address.java
package net.tr.hibernate.entity;

import jakarta.persistence.Embeddable;

@Embeddable
public class Address {
private StringaddressLine1;

private StringaddressLine2;

private Stringcity;

private Stringstate;

private Stringcountry;

private StringzipCode;

Java_ Page 3
private StringzipCode;

public Address() {

public Address(StringaddressLine1, StringaddressLine2, Stringcity, Stringstate, Stringcountry,


StringzipCode) {
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.city = city;
this.state = state;
this.country = country;
this.zipCode = zipCode;
}

public StringgetAddressLine1() {
return addressLine1;
}

public void setAddressLine1(StringaddressLine1) {


this.addressLine1 = addressLine1;
}

public StringgetAddressLine2() {
return addressLine2;
}

public void setAddressLine2(StringaddressLine2) {


this.addressLine2 = addressLine2;
}

public StringgetCity() {
return city;
}

public void setCity(Stringcity) {


this.city = city;
}

public StringgetState() {
return state;
}

public void setState(Stringstate) {


this.state = state;
}

public StringgetCountry() {
return country;
}

public void setCountry(Stringcountry) {


this.country = country;
}

public StringgetZipCode() {
return zipCode;
}

public void setZipCode(StringzipCode) {


this.zipCode = zipCode;
}
}

Name.java
package net.tr.hibernate.entity;

import jakarta.persistence.Embeddable;

@Embeddable
public class Name {
private StringfirstName;

private StringmiddleName;

private StringlastName;

public Name() {

public Name(StringfirstName, StringmiddleName, StringlastName) {


this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}

public StringgetFirstName() {
return firstName;
}

public void setFirstName(StringfirstName) {


this.firstName = firstName;
}

public StringgetMiddleName() {
return middleName;
}

public void setMiddleName(StringmiddleName) {


this.middleName = middleName;
}

public StringgetLastName() {
return lastName;
}

public void setLastName(StringlastName) {


this.lastName = lastName;
}
}

Java_ Page 4
Embedding an Embeddable object with @Embedded
We can simply embed an embeddable class using the @Embedded annotation. This class will be embedded in the same database table as the source. We can
optionally override the attributes of the embedded class using the @AttributeOverrides and @AttributeOverride annotations.

Let's create a User class and embed Address and Name classes into it using the @Embedded annotation:
import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Longid;

@Embedded
private Namename;

private Stringemail;

@Embedded
@AttributeOverrides(value = {
@AttributeOverride(name = "addressLine1", column = @Column(name = "house_number")),
@AttributeOverride(name = "addressLine2", column = @Column(name = "street"))
})
private Addressaddress;

public User() {

public User(Namename, Stringemail, Addressaddress) {


this.name = name;
this.email = email;
this.address = address;
}

public LonggetId() {
return id;
}

public void setId(Longid) {


this.id = id;
}

public NamegetName() {
return name;
}

public void setName(Namename) {


this.name = name;
}

public StringgetEmail() {
return email;
}

public void setEmail(Stringemail) {


this.email = email;
}

public AddressgetAddress() {
return address;
}

public void setAddress(Addressaddress) {


this.address = address;
}
}

Running and Testing Embeddable Objects


When we execute the following application, a record will be added to the database.
package net.tr.embproj;

import org.hibernate.Session;
import org.hibernate.Transaction;

import net.tr.hibernate.entity.Address;
import net.tr.hibernate.entity.Name;
import net.tr.hibernate.entity.User;
import net.tr.hibernate.util.HibernateUtil;

public class App


{
public static void main(String[] args)
{

Namename = new Name("Ramesh", "M", "Fadatare");


Addressaddress = new Address("111", "Puadroad", "Pune", "Maharastra", "India", "411038");
Useruser = new User(name, "[email protected]", address);

Transactiontransaction = null;
try (Sessionsession = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// save the student object
session.persist(user);
// commit transaction
transaction.commit();
} catch (Exceptione) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();

Java_ Page 5
e.printStackTrace();
}
}
}

MySQL Database Table

Output

Java_ Page 6

You might also like