JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-003使用@AttributeOverrides
Each @AttributeOverride for a component property is “complete”: any JPA or Hibernate annotation on the overridden property is ignored. This means the @Column annotations on the Address class are ignored—all BILLING_* columns are NULL able!(Bean Validation still recognizes the @NotNull annotation on the component property, though; Hibernate only overrides persistence annotations.)
1.
1 package org.jpwh.model.simple; 2 3 import org.jpwh.model.Constants; 4 5 import javax.persistence.AttributeOverride; 6 import javax.persistence.AttributeOverrides; 7 import javax.persistence.Column; 8 import javax.persistence.Embedded; 9 import javax.persistence.Entity; 10 import javax.persistence.GeneratedValue; 11 import javax.persistence.Id; 12 import javax.persistence.Table; 13 import java.io.Serializable; 14 import java.math.BigDecimal; 15 16 @Entity 17 @Table(name = "USERS") 18 public class User implements Serializable { 19 20 @Id 21 @GeneratedValue(generator = Constants.ID_GENERATOR) 22 protected Long id; 23 24 public Long getId() { 25 return id; 26 } 27 28 protected String username; 29 30 public User() { 31 } 32 33 public String getUsername() { 34 return username; 35 } 36 37 public void setUsername(String username) { 38 this.username = username; 39 } 40 41 // The Address is @Embeddable, no annotation needed here... 42 protected Address homeAddress; 43 44 public Address getHomeAddress() { 45 return homeAddress; 46 } 47 48 public void setHomeAddress(Address homeAddress) { 49 this.homeAddress = homeAddress; 50 } 51 52 @Embedded // Not necessary... 53 @AttributeOverrides({ 54 @AttributeOverride(name = "street", 55 column = @Column(name = "BILLING_STREET")), // NULLable! 56 @AttributeOverride(name = "zipcode", 57 column = @Column(name = "BILLING_ZIPCODE", length = 5)), 58 @AttributeOverride(name = "city", 59 column = @Column(name = "BILLING_CITY")) 60 }) 61 protected Address billingAddress; 62 63 public Address getBillingAddress() { 64 return billingAddress; 65 } 66 67 public void setBillingAddress(Address billingAddress) { 68 this.billingAddress = billingAddress; 69 } 70 71 public BigDecimal calcShippingCosts(Address fromLocation) { 72 // Empty implementation of business method 73 return null; 74 } 75 76 // ... 77 }
You can do anything you set your mind to, man!