2010-03-19 55 views
1

我有JPA(EclipseLink)的問題。 我無法刪除關聯表。情況是這樣的:JPA關聯表不可刪除

  • 產品1:N至ProductResource
  • 資源1​​:N至ProductResource

我第一次ProductResource的產品和資源屬性。如果我然後嘗試刪除ProductResource對象,則不會發生任何事情(不會生成sql - 沒有例外)。如果我在ProductResource中註釋掉這兩個OneToMany註釋,我可以刪除該對象。當產品和資源屬性未設置時,我也可以刪除該對象。如果我只註釋了資源上方的註釋,則ProductResource對象在刪除產品對象後會被刪除(cascade = CascadeType.ALL)。我希望有人能給我一個提示。謝謝。

產品資源:

public class ProductResource implements Serializable { 
@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.MERGE) 
private Product product; 

@ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.MERGE) 
private Resource resource; 

產品:

public class Product implements Serializable { 

@OneToMany(mappedBy="product", fetch=FetchType.EAGER, cascade=CascadeType.ALL) 
private List<ProductResource> productResources = new ArrayList<ProductResource>(); 

資源:

public class Resource implements Serializable { 

@OneToMany(mappedBy="resource", fetch=FetchType.EAGER, cascade=CascadeType.ALL) 
private List<ProductResource> productResources = new ArrayList<ProductResource>(); 

問候馬塞爾

回答

0

實際上有3個解決方案:

1)刪除孤兒bef您刪除ProductResource對象。產品資源未被刪除的原因是因爲系統中仍存在引用它們的對象。

2)刪除孤兒中對ProductResource對象的引用。這是出於與上述相同的原因。

3)使用JPA批註將產品和資源對象設置爲@PrivateOwned。這將導致孤兒自動被刪除,如果它們存在。這是您可能會或可能不想爲您自動完成的行爲。造成這種情況的原因可能是因爲產品或資源對象不需要對ProductResource存在的引用。這取決於你的設計。

+0

非常感謝您的詳細解釋。起初JPA看起來很容易使用。魔鬼在細節中。非常感謝像你這樣的人花時間幫助像我這樣的新手。 問候馬塞爾 – 2010-03-21 12:45:20

0

下面是溶液:

產品類

@PrivateOwned 
@OneToMany(mappedBy="product", fetch=FetchType.EAGER, cascade=CascadeType.ALL) 
private List<ProductResource> productResources = new ArrayList<ProductResource>(); 

資源類

@PrivateOwned 
@OneToMany(mappedBy="resource", fetch=FetchType.EAGER, cascade=CascadeType.ALL) 
private List<ProductResource> productResources = new ArrayList<ProductResource>(); 

@PrivateOwned是新...

馬塞爾