In this tutorial you will show how to map composite components using Hibernate/JPA Annotations. Consider the following relationship between Worker and WorkerInfo Entity.
According to the relationship each Worker should have a unique WorkerInfo.
So, since the two Entities are strongly related (composition relation), it is better to store them in a single table (named Worker) but you can keep them logically separated in two Entities. Here’s the Worker Entity:
package com.sample; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table public class Worker { private long workerId; private String name; private WorkerInfo info; public Worker() { } public Worker(String name, WorkerInfo info) { this.name = name; this.info = info; } @Id @GeneratedValue @Column(name = "WORKER_ID") public long getStudentId() { return this.workerId; } public void setWorkerId(long workerId) { this.workerId = workerId; } @Column(name = "WORKER_NAME", nullable = false, length = 100) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Embedded public WorkerInfo getWorkerInfo() { return this.info; } public void setStudentAddress(WorkerInfo info) { this.info = info; } }
The @Embedded annotation is used to specify the WorkerInfo entity should be stored in the WORKER table as a component.
@Embeddable annotation is used to specify the WorkerInfo class will be used as a component. The WorkerInfo class cannot have a primary key of its own, it uses the enclosing class primary key.
package com.sample; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class WorkerInfo { private String address; private String city; private String country; public WorkerInfo() { } public WorkerInfo(String street, String city, String state ) { this.address = street; this.city = city; this.country = state; } @Column(name = "INFO_STREET", nullable = false, length=250) public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Column(name = "INFO_CITY", nullable = false, length=50) public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Column(name = "INFO_COUNTRY", nullable = false, length=50) public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }