Hibernate component mapping
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:
1 @Entity 2 public class Husband { 3 private int id; 4 private String name; 5 private Wife wife; 6 @Id 7 @GeneratedValue 8 public int getId() { 9 return id; 10 } 11 public void setId(int id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 @Embedded 21 public Wife getWife() { 22 return wife; 23 } 24 public void setWife(Wife wife) { 25 this.wife = wife; 26 } 27 }
Component Wife:
1 public class Wife { 2 private String wifeName; 3 private int wifeAge; 4 public String getWifeName() { 5 return wifeName; 6 } 7 public void setWifeName(String wifeName) { 8 this.wifeName = wifeName; 9 } 10 public int getWifeAge() { 11 return wifeAge; 12 } 13 public void setWifeAge(int wifeAge) { 14 this.wifeAge = wifeAge; 15 } 16 }
We embed the component wife in entity Husband by @Embedded, So we get only one table named Hunband:
1 create table Husband ( 2 id integer not null auto_increment, 3 name varchar(255), 4 wifeAge integer not null, 5 wifeName varchar(255), 6 primary key (id) 7 )
So, Use component can make our program structual more clear in logic.
create by andy!
-----------if I rest, I rust--------------
浙公网安备 33010602011771号