Wife is a component of Husband class and thus they are stored in one table in DB.
1.Annotation
Husband: put @Embedded before component Wife.
Only need one <mapping class="xxxx.xxx.xxx.Husband"> since wife is part of husband‘s table
@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; } @Embedded public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Wife { private String wifeName; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getWifeName() { return wifeName; } public void setWifeName(String name) { wifeName = name; } }
2.XML
Only Husband needs xml.
<Component name="xx of getXX()"> and list <property name="">
<hibernate-mapping package="com.hibernate.model"> <class name="Husband"> <id name="id"></id> <property name="name"></property> <component name="wife" > <property name ="wifeName"></property> <property name ="age"></property> </component> </class>
时间: 2024-10-08 10:44:13