JPA 注解映射(集合类的使用)
private Collection<CustomerEO> customers = new ArrayList<CustomerEO>();
其中,加粗的部分明确指明了Collection集合对象中存放的是CustomerEO对象。这可以避免在运行时导致的一些异常。
(2)定义时使用接口,初始化使用具体的类。
在定义集合类型时,通常使用接口如Collection、Set、List和Map等,但初始化时要明确指定所使用的类型。
? Collection可以初始化为ArrayList或HashSet,例如:
private Collection<CustomerEO> customers = new ArrayList<CustomerEO>();或者private Collection<CustomerEO> customers = new HashSet<CustomerEO>();
private Set<CustomerEO> customers = new HashSet<CustomerEO>();
private List<CustomerEO> customers = new ArrayList<CustomerEO>();
private Map<String,CustomerEO> customer = new HashMap<String,CustomerEO>();
@Entity@Table(name = "customer")public class CustomerEO implements java.io.Serializable {……private List<AddressEO> addresses = new ArrayList<AddressEO>();@OneToMany(mappedBy="customer")@OrderBy("postcode ASC")public List<AddressEO> getAddresses() {return addresses;} public void setAddresses(List addresses) {this.addresses = addresses;}}
@Entity@Table(name = "customer")public class CustomerEO implements java.io.Serializable {……private Map<Integer,AddressEO> addresses = new HashMap<Integer,AddressEO>(); @OneToMany(mappedBy="customer")@MapKey(name="id")public Map<Integer, AddressEO> getAddresses() {return addresses;} public void setAddresses(Map<Integer, AddressEO> addresses) {this.addresses = addresses;}}