eclipse + JBoss 5 + EJB3开发指南(9) - 编程入门网
eclipse + JBoss 5 + EJB3开发指南(9)时间:2011-09-18 blogjava 哈佛校训实现Entity Bean的多对多(many-to-many)映射 在EJB3中需要使用@ManyToMany对封装多对多关系的字段或getter方法进行注释。先看看下面的表: 图1 t_addresses表 t_addresses表和t_customers表是多对多的关系。需要使用一个关联表来描述这种关系,关联表的结 构如下图所示。 图2 t_customers_addresses 在Customer类中定义一个Collection<Address>类型的字段(addresses),用于保存与该 Customer对象相对应的多个Address对象,代码如下: package entity; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name = "t_customers") public class Customer { private int id; private String name; private Referee referee; private Collection<Order> orders; private Collection<Address> addresses; @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) @JoinTable(name = "t_customers_addresses", joinColumns = @JoinColumn(name = "customer_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "address_id", referencedColumnName = "id")) public Collection<Address> getAddresses() { return addresses; } ... ... } eclipse + JBoss 5 + EJB3开发指南(9)(2)时间:2011-09-18 blogjava 哈佛校训@JoinTable注释用于指定连接表和t_customers及t_addresses表的连接字段关系。 Address类的代码如下: package entity; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="t_addresses") public class Address { private int id; private String addressLine; private String country; private String postCode; private Collection<Customer> customers; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAddressLine() { return addressLine; } public void setAddressLine(String addressLine) { this.addressLine = addressLine; |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |