假设有两个表,订单表
和产品表
,订单跟产品的关系是一对多的关系,那么在JPA中怎样表示一对多的关系呢?实体关系一对多映射有两种方式:
1 外键关联
//订单表
@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;
...
}
//产品表
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
这样在表product
中会增加一列order_id
2 表关联
//订单表
@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
表