标签:
一、数据库
二、代码
1.
1 package org.jpwh.model.advanced; 2 3 import javax.persistence.AttributeOverride; 4 import javax.persistence.AttributeOverrides; 5 import javax.persistence.Column; 6 import javax.persistence.Embeddable; 7 import javax.validation.constraints.NotNull; 8 9 @Embeddable 10 public class Address { 11 12 @NotNull 13 @Column(nullable = false) 14 protected String street; 15 16 @NotNull 17 @AttributeOverrides( 18 @AttributeOverride( 19 name = "name", 20 column = @Column(name = "CITY", nullable = false) 21 ) 22 ) 23 protected City city; 24 25 public String getStreet() { 26 return street; 27 } 28 29 public void setStreet(String street) { 30 this.street = street; 31 } 32 33 public City getCity() { 34 return city; 35 } 36 37 public void setCity(City city) { 38 this.city = city; 39 } 40 41 // ... 42 }
2.
1 package org.jpwh.model.advanced; 2 3 import javax.persistence.Column; 4 import javax.persistence.Embeddable; 5 import javax.validation.constraints.NotNull; 6 7 @Embeddable 8 public class City { 9 10 @NotNull 11 @Column(nullable = false, length = 5) // Override VARCHAR(255) 12 protected String zipcode; 13 14 @NotNull 15 @Column(nullable = false) 16 protected String name; 17 18 @NotNull 19 @Column(nullable = false) 20 protected String country; 21 22 public String getZipcode() { 23 return zipcode; 24 } 25 26 public void setZipcode(String zipcode) { 27 this.zipcode = zipcode; 28 } 29 30 public String getName() { 31 return name; 32 } 33 34 public void setName(String name) { 35 this.name = name; 36 } 37 38 public String getCountry() { 39 return country; 40 } 41 42 public void setCountry(String country) { 43 this.country = country; 44 } 45 46 // ... 47 }
3.
1 package org.jpwh.model.advanced; 2 3 import org.jpwh.model.Constants; 4 5 import javax.persistence.Entity; 6 import javax.persistence.GeneratedValue; 7 import javax.persistence.Id; 8 import javax.persistence.Table; 9 10 @Entity 11 @Table(name = "USERS") 12 public class User { 13 14 @Id 15 @GeneratedValue(generator = Constants.ID_GENERATOR) 16 protected Long id; 17 18 public Long getId() { 19 return id; 20 } 21 22 protected Address address; 23 24 public Address getAddress() { 25 return address; 26 } 27 28 public void setAddress(Address address) { 29 this.address = address; 30 } 31 }
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.
JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-004嵌套组件的注解AttributeOverrides
标签:
原文地址:http://www.cnblogs.com/shamgod/p/5362985.html