一、数据库
二、代码
1.
package org.jpwh.model.advanced; import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull; @Embeddable
public class Address { @NotNull
@Column(nullable = false)
protected String street; @NotNull
@AttributeOverrides(
@AttributeOverride(
name = "name",
column = @Column(name = "CITY", nullable = false)
)
)
protected City city; public String getStreet() {
return street;
} public void setStreet(String street) {
this.street = street;
} public City getCity() {
return city;
} public void setCity(City city) {
this.city = city;
} // ...
}
2.
package org.jpwh.model.advanced; import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull; @Embeddable
public class City { @NotNull
@Column(nullable = false, length = 5) // Override VARCHAR(255)
protected String zipcode; @NotNull
@Column(nullable = false)
protected String name; @NotNull
@Column(nullable = false)
protected String country; public String getZipcode() {
return zipcode;
} public void setZipcode(String zipcode) {
this.zipcode = zipcode;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getCountry() {
return country;
} public void setCountry(String country) {
this.country = country;
} // ...
}
3.
package org.jpwh.model.advanced; import org.jpwh.model.Constants; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name = "USERS")
public class User { @Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; public Long getId() {
return id;
} protected Address address; public Address getAddress() {
return address;
} public void setAddress(Address address) {
this.address = address;
}
}
You can declare @AttributeOverride s at any level, as you do for the name property of the City class, mapping it to the CITY column. This can be achieved with either (as shown) an @AttributeOverride in Address or an override in the root entity class,User . Nested properties can be referenced with dot notation: for example, on User#address , @AttributeOveride(name = "city.name") references the Address #City#name attribute.