原文:http://blog.sina.com.cn/s/blog_6fef491d0100obdd.html
终于要说ManyToMany了
场景:Product和Customer。
先看TestProduct.java
1 package net.paoding.forum.domain; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import javax.persistence.Entity; 7 import javax.persistence.Id; 8 import javax.persistence.ManyToMany; 9 10 @Entity 11 public class TestProduct 12 { 13 private String id; 14 private String name; 15 private float price; 16 private List<TestCustomer> customers = new ArrayList<TestCustomer>(); 17 18 19 @Id 20 public String getId() 21 { 22 return id; 23 } 24 25 26 public void setId(String id) 27 { 28 this.id = id; 29 } 30 31 32 public String getName() 33 { 34 return name; 35 } 36 37 38 public void setName(String name) 39 { 40 this.name = name; 41 } 42 43 44 public float getPrice() 45 { 46 return price; 47 } 48 49 50 public void setPrice(float price) 51 { 52 this.price = price; 53 } 54 55 56 @ManyToMany 57 public List<TestCustomer> getCustomers() 58 { 59 return customers; 60 } 61 62 63 public void setCustomers(List<TestCustomer> customers) 64 { 65 this.customers = customers; 66 } 67 68 }
注意这里的ManyToMany什么都没有写。
再看TestCustomer.java
1 package net.paoding.forum.domain; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import javax.persistence.Entity; 7 import javax.persistence.Id; 8 import javax.persistence.ManyToMany; 9 10 @Entity 11 public class TestCustomer 12 { 13 private String id; 14 private String tel; 15 private List<TestProduct> products = new ArrayList<TestProduct>(); 16 17 18 @Id 19 public String getId() 20 { 21 return id; 22 } 23 24 25 public void setId(String id) 26 { 27 this.id = id; 28 } 29 30 31 public String getTel() 32 { 33 return tel; 34 } 35 36 37 public void setTel(String tel) 38 { 39 this.tel = tel; 40 } 41 42 43 @ManyToMany(mappedBy = "customers") 44 public List<TestProduct> getProducts() 45 { 46 return products; 47 } 48 49 50 public void setProducts(List<TestProduct> products) 51 { 52 this.products = products; 53 } 54 }
这里的ManyToMany我写了mappedBy这个attribute。
然后看hib产生的sql:
1 drop table test_customer cascade constraints; 2 drop table test_product cascade constraints; 3 drop table test_product_customers cascade constraints; 4 5 create table test_customer ( 6 id varchar2(255 char) not null, 7 tel varchar2(255 char), 8 primary key (id) 9 ); 10 11 create table test_product ( 12 id varchar2(255 char) not null, 13 price float not null, 14 name varchar2(255 char), 15 primary key (id) 16 ); 17 18 create table test_product_customers ( 19 products_id varchar2(255 char) not null, 20 customers_id varchar2(255 char) not null 21 );
ok! 非常好。hib终于在ManyToMany上没有犯白痴了。
上面强调了mappedBy这个属性。其实,在annotation 系列中。都有提到mappedBy这个东西。只是,我没有说到底是什么意思。其实很简单:这个东西就相当于xml配置中的inverse。写了mappedBy就代表这个方法的返回值是被维护方