Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Saturday

JPA (Java Persistence API) Tutorial Embedded Objects

Embedded Objects

Embedded Objects is a way to organize entities that have different data in the same table. Imagine a database
table that maintains "person" information (e.g. name, age) and address data (street name, house number, city etc).

It is possible to see data related to a person and their corresponding address also. Check the code below to see an
example of how to implement the Embedded Objects concept with the Person and Address entities:

import javax.persistence.*;
@Embeddable
public class Address {
@Column(name = "house_address")
private String address;
@Column(name = "house_color")
private String color;
@Column(name = "house_number")
private int number;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
// get and set
}
import javax.persistence.*;
@Entity
@Table(name = "person")
public class Person {
@Id
private int id;
private String name;

private int age;
@Embedded
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
// get and set
}

About the code above:
•The @Embeddable annotation (Address class) allows the class to be used inside an entity,
notice that Address is not an entity. It is just a class to help organize the database data.
•A @Column annotation is used in the Address class to indicate the table database column
name.
•The @Embedded annotation (Person entity) indicates that JPA will map all the fields that are
inside the Address class as belonging to the Person entity.
•The Address class can be used in other entities. There are ways to override the @Column

annotation at runtime.

NEXT


No comments:

Post a Comment