假設(shè)有兩個表滞时,訂單表
和產(chǎn)品表
掰担,訂單跟產(chǎn)品的關(guān)系是一對多的關(guān)系,那么在JPA中怎樣表示一對多的關(guān)系呢晃财?實體關(guān)系一對多映射有兩種方式:
1 外鍵關(guān)聯(lián)
//訂單表
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = {CascadeType.ALL})
@JoinColumn(name = "order_id")
private List<Product> productList;
...
}
//產(chǎn)品表
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
這樣在表product
中會增加一列order_id
2 表關(guān)聯(lián)
//訂單表
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "order_has_product", joinColumns = {@JoinColumn(name = "order_id", referencedColumnName = "id")},inverseJoinColumns = {@JoinColumn(name = "product_id", referencedColumnName = "id")})
private List<Product> productList;
...
}
這樣在product
表中不會增加任何外鍵痹升,而是新建了一張order_has_product
表