@Entity 數據庫
@Table(name="orders")
public class Order {
//1-m,多的一方爲關係維護端,關係維護端負責外鍵記錄的更新,關係被維護端沒有權利更新外鍵記錄
private String orderid;
private Float amount;
private Set<OrderItem> items = new HashSet<OrderItem>();
@Id @Column(length=12)
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
@Column(nullable=false)
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
@OneToMany(cascade={CascadeType.REFRESH,CascadeType.PERSIST,CascadeType.REMOVE,CascadeType.MERGE},fetch=FetchType.LAZY,mappedBy="order")//出現mapby爲被維護端|||默認爲延遲加載
public Set<OrderItem> getItems() {
return items;
}
public void setItems(Set<OrderItem> items) {
this.items = items;
}
public void addOrderItem(OrderItem orderItem){
orderItem.setOrder(this);
this.items.add(orderItem);
}app
}fetch
@Entity
public class OrderItem {
private Integer id;
private String productName;
private Float sellPrice = 0f;
private Order order;
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=40,nullable=false)
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Column(nullable=false)
public Float getSellPrice() {
return sellPrice;
}
public void setSellPrice(Float sellPrice) {
this.sellPrice = sellPrice;
}
@ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=true)
@JoinColumn(name="order_id")
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
this
}spa
CascadeType.REFRESH:級聯刷新,當多個用戶同時做操做一個實體,爲了用戶取到的數據是實時的,在用實體中的數據以前就能夠調用一下refresh()方法!.net
CascadeType.REMOVE:級聯刪除,當調用remove()方法刪除Order實體時會先級聯刪除OrderItem的相關數據!orm
CascadeType.MERGE:級聯更新,當調用了Merge()方法,若是Order中的數據改變了會相應的更新OrderItem中的數據,ci
CascadeType.ALL:包含以上全部級聯屬性。rem
(注:以上幾種級聯操做,只能實在知足數據庫的約束時才能生效,好比上邊的Order和OrderItem存在主外鍵關聯因此執行REMOVE()方法時是不能實現級聯刪除的)get
CascadeType.PERSIST:級聯保存,當調用了Persist() 方法,會級聯保存相應的數據