组件映射,一个类是另外一个类的一部分,比如学生证类是学生类的一部分,在表里的关系,学生证信息的学生表信息的一部分,此时就需要用组件映射,
本例中,wife是husband的一部分。
Wife类:
package com.oracle.hibernate; /** * wife是husband的一部分 * wife示husband属性表的一部分, *所以wife没有id */ public class Wife { /** * 注意wife类里的属性名不能和husband类里的属性名冲突 * 如果属性名一样,可以在getName()上加@Column指定映射的表里的字段名 */ 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; } }
Husband类:
package com.oracle.hibernate; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.OneToOne; @Entity public class Husband { private int id; private String name; private Wife wife; @Id //主键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; } /** * Wife是husband的一部分,wife是husband表的一部分 * 比如学生证信息,完全可以写在学生表里,作为属性的一部分, * 能写在一张表里就不必单独再弄一张表 * * 用@Embedded,嵌入的 */ @Embedded public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } }
生成的表是一张表husband:
hibernate建表语句:
create table Husband (
id integer not null auto_increment,
name varchar(255),
wifeName varchar(255),
wifeage integer not null,
primary key (id)
)