一、嵌入对象
在“复合主键”章节中,我们看到了怎样用嵌入对象和 @EmbeddedId 注解。
嵌入对象自己没有持久化 ID ,共享被嵌入实体类的 ID 。如果该实体类被删除,嵌入对象也被删除。
请看下例:
@Embeddable
public class Address {
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;
// Constructors, getters, setters
}
@Entity
public class Customer {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Embedded
private Address address;
// Constructors, getters, setters
}
每一个 Address 的属性都会被映射到实体类 Customer 对应的表中。
产生的 DDL :
CREATE TABLE `customer` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`city` varchar(255) DEFAULT NULL,
`country` varchar(255) DEFAULT NULL,
`state` varchar(255) DEFAULT NULL,
`street1` varchar(255) DEFAULT NULL,
`street2` varchar(255) DEFAULT NULL,
`zipcode` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`phoneNumber` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)
二、嵌入对象类的访问类型
一个嵌入对象类的访问类型默认由被其嵌入的实体类访问类型决定。如果实体类显示使用属性访问类型,嵌入对象将隐式同样使用属性访问。如果想让嵌入对象有不同的访问类型,可以通过 @Access 注解指定。
看下例: Customer 实体和 Address 实体有不同的访问类型。
@Entity
@Access(AccessType.FIELD)
public class Customer {
@Id
@GeneratedValue
private Long id;
@Column(name = "first_name", nullable = false, length = 50)
private String firstName;
@Column(name = "last_name", nullable = false, length = 50)
private String lastName;
private String email;
@Column(name = "phone_number", length = 15)
private String phoneNumber;
@Embedded
private Address address;
// Constructors, getters, setters
}
@Embeddable
@Access(AccessType.PROPERTY)
public class Address {
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;
// Constructors
@Column(nullable = false)
public String getStreet1() {
return street1;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
@Column(nullable = false, length = 50)
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Column(length = 3)
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Column(name = "zip_code", length = 10)
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
显示的设置嵌入对象的访问类型是极力推荐的,这样会避免嵌入对象被嵌入到多个实体类中产生映射问题。