在实际开发过程中,JPA多对一单向关联是使用最多的关联方式。
下面是订单与订单项的配置关系。
订单(Order):一的一方,不进行任何配置
-
@Entity
-
@Table(name=
"orders")
-
public
class Order {
-
-
@Id
-
@Column(length=
40)
-
private String orderId;
//订单ID
-
-
@Column(nullable=
false)
-
private Float amount =
0f;
//总价
-
-
private Set<OrderItem> items;
//订单项(可有可无,查询订单时,无法查出此项)
-
-
public String getOrderId() {
-
return orderId;
-
}
-
-
public void setOrderId(String orderId) {
-
this.orderId = orderId;
-
}
-
public Float getAmount() {
-
return amount;
-
}
-
-
public void setAmount(Float amount) {
-
this.amount = amount;
-
}
-
-
public Set<OrderItem> getItems() {
-
return items;
-
}
-
-
public void setItems(Set<OrderItem> items) {
-
this.items = items;
-
}
订单项(OrderItem):多的一方,进行ManyToOne关联配置。
-
@Entity
-
public
class OrderItem {
-
-
@Id
-
@GeneratedValue
//ID自增长
-
private Integer id;
-
-
@Column(length=
40,nullable=
false)
-
private String productName;
-
-
@Column(nullable=
false)
-
private Float sellPrice;
-
-
/*
-
* @JoinColumn(name="order_id") 数据库中外键的名字为order_id
-
*/
-
@ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},
-
fetch=FetchType.EAGER,optional=
false)
-
@JoinColumn(name=
"order_id")
-
private Order order;
-
-
public Integer getId() {
-
return id;
-
}
-
-
public void setId(Integer id) {
-
this.id = id;
-
}
-
public String getProductName() {
-
return productName;
-
}
-
-
public void setProductName(String productName) {
-
this.productName = productName;
-
}
-
public Float getSellPrice() {
-
return sellPrice;
-
}
-
-
public void setSellPrice(Float sellPrice) {
-
this.sellPrice = sellPrice;
-
}
-
-
public Order getOrder() {
-
return order;
-
}
-
-
public void setOrder(Order order) {
-
this.order = order;
-
}
原文地址:https://blog.csdn.net/u011983531/article/details/48728761