@JoinTable注释用于指定连接表和t_customers及t_addresses表的连接字段关系。 Address类的代码如下:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> 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 StringaddressLine; private Stringcountry; private StringpostCode; private Collection < Customer > customers; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId( int id) { this .id = id; } public StringgetAddressLine() { return addressLine; } public void setAddressLine(StringaddressLine) { this .addressLine = addressLine; } public StringgetCountry() { return country; } public void setCountry(Stringcountry) { this .country = country; } public StringgetPostCode() { return postCode; } public void setPostCode(StringpostCode) { this .postCode = postCode; }@ManyToMany(mappedBy ="addresses" ) public Collection < Customer > getCustomers() { return customers; } public void setCustomers(Collection < Customer > customers) { this .customers = customers; } }由于是多对多的关系,因此,在Address类中需要定义一个Collection<Customer>类型的字段(customers)用来保存与该Address对象相对应的Customer对象。getCustomers方法也需要使用@ManyToMany进行注释。可以使用下面代码进行测试: <!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> Customercustomer = new Customer(); customer.setName( " 微软11 " ); List < Address > addresses = new ArrayList < Address > (); Addressaddress = new entity.Address(); address.setAddressLine( " address1 " ); address.setCountry( " 中国 " ); address.setPostCode( " 12345678 " ); addresses.add(address); address = new entity.Address(); address.setAddressLine( " address2 " ); address.setCountry( " 美国 " ); address.setPostCode( " 4321 " ); addresses.add(address); customer.setAddresses(addresses); em.persist(customer); 下一篇: eclipse + JBoss 5 + EJB3开发指南(9):实现Entity Bean的多对多(many-to-many)映射 国内最棒的Google Android技术社区(eoeandroid),欢迎访问! 《银河系列原创教程》发布 《Java Web开发速学宝典》出版,欢迎定购 相关资源:敏捷开发V1.0.pptx
