eclipse + JBoss 5 + EJB3开发指南(8) - 编程入门网
eclipse + JBoss 5 + EJB3开发指南(8)时间:2011-09-18 blogjava 哈佛校训实现Entity Bean的一对多(one-to-many)映射 EJB3的一对多映射使用@OneToMany来设置,如果是双向的一对多映射,在many方需要使用@ManyToOne 设置。在本书中给出两个表,其他一个表t_customers在上一篇文章中已给出了,另一个表的结构如图1所 示。 图1 t_orders表 t_customers和t_orders表是一对多关系,一个Customer可能有多个Order,而一个Order只能有一个 Customer。 在Customer类中需要定义一个集合类型的属性,用来保存多个Order对象,Customer类的代码如下: 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; @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL) public Collection<Order> getOrders() { return orders; } public void setOrders(Collection<Order> orders) { this.orders = orders; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } ... ... } eclipse + JBoss 5 + EJB3开发指南(8)(2)时间:2011-09-18 blogjava 哈佛校训其中@OneToMany的mappedBy属性指定了Order类中获得Customer对象的属性名。Order类的代码如下: package entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "t_orders") public class Order { private int id; private String productId; private int count; private Customer customer; @ManyToOne @JoinColumn(name = "customer_id") public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } ... ... } eclipse + JBoss 5 + EJB3开发指南(8)(3)时间:2011-09-18 blogjava 哈 |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |