组件(Component)类必须在类一级定义
@Embeddable
注解.
在特定的实体的关联属性上使
@Embedded
和
@AttributeOverride
注解可以覆盖该属性对应的嵌入式对象的字段映射:
@Entity
public
class
Person
implements
Serializable {
//
Persistent component using defaults
Address homeAddress;
@Embedded
@AttributeOverrides( {
@AttributeOverride(name
=
"
iso2
"
, column
=
@Column(name
=
"
bornIso2
"
) ),
@AttributeOverride(name
=
"
name
"
, column
=
@Column(name
=
"
bornCountryName
"
) )
} )
Country bornIn;
}
@Embeddable
public
class
Address
implements
Serializable {
String city;
Country nationality;
//
no overriding here
}
@Embeddable
public
class
Country
implements
Serializable {
private
String iso2;
@Column(name
=
"
countryName
"
)
private
String name;
public
String getIso2() {
return
iso2; }
public
void
setIso2(String iso2) {
this
.iso2
=
iso2; }
public
String getName() {
return
name; }
public
void
setName(String name) {
this
.name
=
name; }
}
说明:
1.
Person
有两个组件属性,分别是
homeAddress
和
bornIn
.
homeAddress
属性并没有注解. 但是Hibernate自动检测其对应的Address类中的
@Embeddable
注解, 并将其看作一个持久化组件.
2.对于Country中已映射的属性,则使用
@Embedded
和
@AttributeOverride
注解来覆盖原来的字段映射值。
3.
Address
对象中还内嵌了
Country
对象,
Hibernate通过在表达式中使用"."支持覆盖多层嵌套(即嵌入式对象中还包括其他嵌入式对象)的字段映射.如下:
@Embedded
@AttributeOverrides( {
@AttributeOverride(name
=
"
city
"
, column
=
@Column(name
=
"
fld_city
"
) )
@AttributeOverride(name
=
"
nationality.iso2
"
, column
=
@Column(name
=
"
nat_Iso2
"
) ),
@AttributeOverride(name
=
"
nationality.name
"
, column
=
@Column(name
=
"
nat_CountryName
"
) )
//
nationality columns in homeAddress are overridden
} )
Address homeAddress;