JPA,在@OneToMany里加入mappedBy属性

JPA,在@OneToMany里加入mappedBy属性避免生成中间表

使用JPA的时候,如果A B两个实体间是一对多,多对一的关系,如果不在@OneToMany里加入mappedBy属性(相当于inverse=”true”)会导致自动生成一个多余的中间表。比如:

 

@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表。
又如:
In Customer class

@OneToMany(cascade=ALL, mappedBy="customer")
public  Set getOrders() { 
	return orders; 
}

In Order class

@ManyToOne
@JoinColumn(name="CUST_ID", nullable=false)
public Customer getCustomer() { 
	return customer; 
}

mappedBy=”customer”
说明在两个关联的实体Bean中,orders这一端是关系的拥有者,Orders一方的表中生成到关联类的外键
且mappedBy只有在双向关联时,才会使用这个属性
cascade=ALL
说明,当Orders做CRUD操作时,Customer都会进行相应操作

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s