2017-10-16 156 views
1

我有ManyToOne映射,我希望刪除所有的子元素刪除父。我看到了一個關於here的解決方案,並且知道沒有必要有雙向關係來實現這樣的邏輯,但它不適用於我的情況。休眠@OnDelete(動作= OnDeleteAction.CASCADE)不起作用

import javax.persistence.ManyToOne; 
import javax.persistence.SequenceGenerator; 
import javax.persistence.Table; 
import org.hibernate.annotations.Cascade; 
import org.hibernate.annotations.CascadeType; 
import org.hibernate.annotations.OnDelete; 
import org.hibernate.annotations.OnDeleteAction; 

@Entity 
@Table(name="SubOrder") 
public class SubOrder { 

@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="order_seq") 
@SequenceGenerator(name = "order_seq", initialValue=1000000000, allocationSize=1, sequenceName="order_auto_seq") 
@Column(name="sub_order_id") 
private long subOrder; 

@Column(name="product_name" , length=50) 
private String productName; 

@Column(name="Date") 
private String date; 

@ManyToOne() 
@Cascade({CascadeType.PERSIST}) 
@OnDelete(action = OnDeleteAction.CASCADE) 
private Order order; 

public Order getOrder() { 
    return order; 
} 

//Getters and setters 

下面是我的父類

@Entity 
@Table(name="Orders") 
public class Order { 

@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="order_seq") 
@SequenceGenerator(name = "order_seq", initialValue=1000000000, allocationSize=1, sequenceName="order_auto_seq") 
@Column(name="order_number") 
private long orderNumber; 

@Temporal(TemporalType.TIMESTAMP) 
@Column(name="Order_date") 
private Date date= new Date(); 

//Getters and setters 

我刪除代碼

Order result =session.get(Order.class, 1000000000l); 
session.delete(result); 

上面的代碼刪除訂單(父),而不是子元素。

我的休眠,cfg.file

<property name="hbm2ddl.auto">update</property> 

出了什麼問題嗎?

回答

0

我發現了這個錯誤。我依靠Hibernate在創建表時創建級聯關係,這並沒有發生。我必須通過指定

`FOREIGN KEY (order_order_number) REFERENCES orders (order_number) 
    ON DELETE CASCADE 
    ON UPDATE CASCADE` 

在MySql中創建子表時創建表。之後它開始工作。