A Component is a containted object that is be persisted value type and not an entity.But you can embed the component to entity.
Now We need one-to-one association for husband an wife. We just let the in one table. Then we create one entity, on component.
such as this:
Entity Husband:
@Entity
public class Husband {
private int id;
private String name;
private Wife wife;
@Id
@GeneratedValue
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;
}
@Embedded
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
}
Component Wife:
public class Wife {
private String wifeName;
private int wifeAge;
public String getWifeName() {
return wifeName;
}
public void setWifeName(String wifeName) {
this.wifeName = wifeName;
}
public int getWifeAge() {
return wifeAge;
}
public void setWifeAge(int wifeAge) {
this.wifeAge = wifeAge;
}
}
We embed the component wife in entity Husband by @Embedded, So we get only one table named Hunband:
create table Husband (
id integer not null auto_increment,
name varchar(255),
wifeAge integer not null,
wifeName varchar(255),
primary key (id)
)
So, Use component can make our program structual more clear in logic.