实体bean(五)一对多
一对多单向关联---采用中间表,用主键对应来关联。
一对多双向关联----采用外键,在一的一方写mappedBy。不需要中间表。
其中定义mappedBy的是@OneToMany,也就是说One这一方是关系的拥有者。Many一方的表中生成到关联类的外键。
以下来自http://hi.baidu.com/linjk03/blog/item/3f05541316b9bc856538db86.html
JPA,在@OneToMany里加入mappedBy属性避免生成中间表
使用JPA的时候,如果A B两个实体间是一对多,多对一的关系,如果不在@OneToMany里加入mappedBy属性会导致自动生成一个多余的中间表。比如:
@Entity public class A { @OneToMany(mappedBy="a") public Set<B> bs = new HashSet<B>(0); } @Entity public class B { @ManyToOne public A a; }
这样写会只成生成表A和表B,B中会有一个到表A的外键。但是如果不加mappedBy=”a”, 那么就会再生成一张A_B表。
——————————————————————————————————————————————————————————————
转http://sulong.javaeye.com/blog/145345
用JoinColumn使用JPA的OneToMany不自动生成数据库表
有两个实体Order和Customer,一个用户可以有多个订单,一个订单属于一个用户,所以Customer与Order是一对多的关系,那么在Order实体里可以有一个到Customer的引用customer,同时在Customer里有一个Order实体的集合orders。如果在只是如下这样写:
public class Order { @id private long id; @ManyToOne private Customer customer; public void setId(long id) { this.id = id; } public long getId() { return this.id; } public void setCustomer(Customer customer) { this.customer = customer; } public Customer getCustomer() { return this.customer; } } public class Customer{ @id private long id; @OneToMany private Set<Order> orders; public void setId(long id) { this.id = id; } public long getId() { return this.id; } public void setOrders(Set<Order> orders) { this.orders = orders; } public Set<Order> getOrders() { return this.orders; } }
那么系统可能会自动生成一张Customer_Order关联表,可是事实上我们不需要这样的表,因为通过 Select order from Order order where order.customer.id=:id, 就可以找到某个Customer的Orders,而不需要另建一张表。要想去掉这个自动生成的表,要这样写:
public class Order { @id private long id; @ManyToOne @JoinColumn(name="customer", nullable=false) private Customer customer; public void setId(long id) { this.id = id; } public long getId() { return this.id; } public void setCustomer(Customer customer) { this.customer = customer; } public Customer getCustomer() { return this.customer; } } public class Customer{ @id private long id; @OneToMany(mappedBy="customer") private Set<Order> orders; public void setId(long id) { this.id = id; } public long getId() { return this.id; } public void setOrders(Set<Order> orders) { this.orders = orders; } public Set<Order> getOrders() { return this.orders; } }
多出一个mappedBy和JoinColumn, 就是告诉JPA实现者,orders是通过order里的customer映射来的,每次查找orders通过Order里的customer联接。这样就不会生成Customer_Order关联表了