原文:http://blog.sina.com.cn/s/blog_6fef491d0100obdd.html
终于要说ManyToMany了
场景:Product和Customer。
先看TestProduct.java
package net.paoding.forum.domain; import java.util.ArrayList;
import java.util.List; import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany; @Entity
public class TestProduct
{
private String id;
private String name;
private float price;
private List<TestCustomer> customers = new ArrayList<TestCustomer>(); @Id
public String getId()
{
return id;
} public void setId(String id)
{
this.id = id;
} public String getName()
{
return name;
} public void setName(String name)
{
this.name = name;
} public float getPrice()
{
return price;
} public void setPrice(float price)
{
this.price = price;
} @ManyToMany
public List<TestCustomer> getCustomers()
{
return customers;
} public void setCustomers(List<TestCustomer> customers)
{
this.customers = customers;
} }
注意这里的ManyToMany什么都没有写。
再看TestCustomer.java
package net.paoding.forum.domain; import java.util.ArrayList;
import java.util.List; import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany; @Entity
public class TestCustomer
{
private String id;
private String tel;
private List<TestProduct> products = new ArrayList<TestProduct>(); @Id
public String getId()
{
return id;
} public void setId(String id)
{
this.id = id;
} public String getTel()
{
return tel;
} public void setTel(String tel)
{
this.tel = tel;
} @ManyToMany(mappedBy = "customers")
public List<TestProduct> getProducts()
{
return products;
} public void setProducts(List<TestProduct> products)
{
this.products = products;
}
}
这里的ManyToMany我写了mappedBy这个attribute。
然后看hib产生的sql:
drop table test_customer cascade constraints;
drop table test_product cascade constraints;
drop table test_product_customers cascade constraints; create table test_customer (
id varchar2(255 char) not null,
tel varchar2(255 char),
primary key (id)
); create table test_product (
id varchar2(255 char) not null,
price float not null,
name varchar2(255 char),
primary key (id)
); create table test_product_customers (
products_id varchar2(255 char) not null,
customers_id varchar2(255 char) not null
);
ok! 非常好。hib终于在ManyToMany上没有犯白痴了。
上面强调了mappedBy这个属性。其实,在annotation 系列中。都有提到mappedBy这个东西。只是,我没有说到底是什么意思。其实很简单:这个东西就相当于xml配置中的inverse。写了mappedBy就代表这个方法的返回值是被维护方